Skip to content

fix: add unit test for check the id on event listener#565

Open
andrestejerina97 wants to merge 1 commit into
mainfrom
fix/add-unit-test-for-event-listener
Open

fix: add unit test for check the id on event listener#565
andrestejerina97 wants to merge 1 commit into
mainfrom
fix/add-unit-test-for-event-listener

Conversation

@andrestejerina97

@andrestejerina97 andrestejerina97 commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Bug Fixes

    • Improved audit handling so test runs skip audit processing more reliably.
    • Updated audit event processing to better preserve created-item details through flush operations.
  • Refactor

    • Simplified audit listener logic by moving the test-skip check into a dedicated helper.
    • Made selected audit-related methods overridable for easier extension in derived components.
  • Tests

    • Added coverage for audit buffering and dispatch during flush/post-flush processing.

@coderabbitai

coderabbitai Bot commented Jun 25, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

AuditEventListener now extracts its testing-environment guard into a helper, makes two internal methods overridable, and adds a unit test covering buffered creation audits during onFlush() with Doctrine insertions.

Changes

Audit listener changes

Layer / File(s) Summary
Skip helper and protected hooks
app/Audit/AuditEventListener.php
onFlush() returns early through shouldSkipInTest(), and getAuditStrategy() plus buildAuditContext() are now protected.
Creation audit onFlush test
tests/OpenTelemetry/Formatters/AuditEventListenerTest.php
The test imports Doctrine event args and AuditContext, then adds a case that mocks scheduled insertions and asserts the audited subject id is not null and not 0.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 I hopped through onFlush with a tidy little skip,
Protected hooks now wiggle, and tests give a thump and trip.
I sniffed the audit trail as inserts sprang to life,
No pre-insert bunny id escaped my gentle strife. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is clearly related to the main change: adding an event-listener unit test around the id check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/add-unit-test-for-event-listener

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

📘 OpenAPI / Swagger preview

➡️ https://OpenStackweb.github.io/summit-api/openapi/pr-565/

This page is automatically updated on each push to this PR.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/OpenTelemetry/Formatters/AuditEventListenerTest.php`:
- Around line 225-267: The test in AuditEventListenerTest is asserting a
deferred “buffer then dispatch” flow, but AuditEventListener::onFlush currently
audits entity insertions immediately, so the captured ID will still be 0. Update
the test to match the actual behavior or, if buffering is intended, add the
missing postFlush dispatch path in AuditEventListener and move the audit call
out of onFlush. Also fix the assertion logic/messages so they reflect the real
expectation around when IAuditStrategy::audit is invoked and what ID value
should be observed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 368f12d9-43c3-4726-8852-951776905f9b

📥 Commits

Reviewing files that changed from the base of the PR and between 5d711e3 and 975210b.

📒 Files selected for processing (2)
  • app/Audit/AuditEventListener.php
  • tests/OpenTelemetry/Formatters/AuditEventListenerTest.php

Comment on lines +225 to +267
public function testCreationAuditIsBufferedInOnFlushAndDispatchedInPostFlush(): void
{
// Simulate a new entity not yet persisted: getId() returns 0 (pre-INSERT state).
$entity = $this->getMockBuilder(\models\summit\SummitEvent::class)
->disableOriginalConstructor()
->onlyMethods(['getId'])
->getMock();
$entity->method('getId')->willReturn(0);

$uow = $this->createMock(UnitOfWork::class);
$uow->method('getScheduledEntityInsertions')->willReturn([$entity]);
$uow->method('getScheduledEntityUpdates')->willReturn([]);
$uow->method('getScheduledEntityDeletions')->willReturn([]);
$uow->method('getScheduledCollectionDeletions')->willReturn([]);
$uow->method('getScheduledCollectionUpdates')->willReturn([]);

$em = $this->createMock(EntityManagerInterface::class);
$em->method('getUnitOfWork')->willReturn($uow);

$strategy = $this->createMock(IAuditStrategy::class);

$listener = $this->getMockBuilder(AuditEventListener::class)
->onlyMethods(['shouldSkipInTest', 'getAuditStrategy', 'buildAuditContext'])
->getMock();
$listener->method('shouldSkipInTest')->willReturn(false);
$listener->method('getAuditStrategy')->willReturn($strategy);
$listener->method('buildAuditContext')->willReturn(new AuditContext());

$capturedId = null;
$strategy->method('audit')->willReturnCallback(
function ($subject) use (&$capturedId) {
$capturedId = method_exists($subject, 'getId') ? $subject->getId() : null;
}
);

$listener->onFlush(new OnFlushEventArgs($em));

// Bug: audit() was called during onFlush — before the INSERT — so the captured id is 0.
$this->assertNotNull($capturedId,
'audit() must not be called during onFlush (INSERT has not run yet)');
$this->assertNotEquals(0, $capturedId,
'entity id captured during onFlush is 0 — the INSERT has not assigned the real id yet');
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP '\b(postFlush|getSubscribedEvents|buffer|deferred?)\b' app/Audit/AuditEventListener.php
ast-grep outline app/Audit/AuditEventListener.php

Repository: OpenStackweb/summit-api

Length of output: 208


🏁 Script executed:

ast-grep outline app/Audit/AuditEventListener.php

Repository: OpenStackweb/summit-api

Length of output: 208


🏁 Script executed:

sed -n '/function onFlush/,/^    }$/p' app/Audit/AuditEventListener.php

Repository: OpenStackweb/summit-api

Length of output: 2213


🏁 Script executed:

#!/bin/bash
# Inspect the specific test logic to confirm the assertion contradiction
sed -n '225,267p' tests/OpenTelemetry/Formatters/AuditEventListenerTest.php

Repository: OpenStackweb/summit-api

Length of output: 2257


Production listener ignores intended "buffer then dispatch" strategy; test assertions and messages are inverted.

The onFlush implementation in app/Audit/AuditEventListener.php executes audits immediately during the onFlush event:

foreach ($uow->getScheduledEntityInsertions() as $entity) {
    $strategy->audit($entity, [], IAuditStrategy::EVENT_ENTITY_CREATION, $ctx);
}

There is no buffering logic or postFlush subscriber method to defer this until the database INSERT completes. Consequently, the test testCreationAuditIsBufferedInOnFlushAndDispatchedInPostFlush correctly captures the pre-INSERT ID 0, causing the assertNotEquals(0, $capturedId) to fail.

Additionally, the assertion messages are logically inverted:

  • assertNotNull passes if audit runs, yet the message claims "must not be called".
  • assertNotEquals fails because ID IS 0, yet the message states "INSERT has not assigned the real id yet" as if asserting a success condition.

Align the assertion logic with the current behavior or implement the deferred postFlush dispatching if that is the desired requirement.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/OpenTelemetry/Formatters/AuditEventListenerTest.php` around lines 225 -
267, The test in AuditEventListenerTest is asserting a deferred “buffer then
dispatch” flow, but AuditEventListener::onFlush currently audits entity
insertions immediately, so the captured ID will still be 0. Update the test to
match the actual behavior or, if buffering is intended, add the missing
postFlush dispatch path in AuditEventListener and move the audit call out of
onFlush. Also fix the assertion logic/messages so they reflect the real
expectation around when IAuditStrategy::audit is invoked and what ID value
should be observed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant