Skip to content

[OPIK-2856] [BE] Refactor test code to use TraceResourceClient instead of direct URL_TEMPLATE calls#3947

Merged
thiagohora merged 25 commits intomainfrom
thiaghora/OPIK-2856-refactor-traces-resource-test-url-template
Nov 5, 2025
Merged

[OPIK-2856] [BE] Refactor test code to use TraceResourceClient instead of direct URL_TEMPLATE calls#3947
thiagohora merged 25 commits intomainfrom
thiaghora/OPIK-2856-refactor-traces-resource-test-url-template

Conversation

@thiagohora
Copy link
Copy Markdown
Contributor

@thiagohora thiagohora commented Nov 5, 2025

Details

This PR refactors test code to use TraceResourceClient instead of direct HTTP client calls with URL_TEMPLATE, improving code maintainability and reducing duplication. Also, move the get trace threads tests to FindTraceThreadsResourceTest.

Changes Made

  1. TracesResourceTest.java - Removed URL_TEMPLATE usage

    • Replaced all direct client.target(URL_TEMPLATE) calls with traceResourceClient methods
    • Created new methods in TraceResourceClient to encapsulate HTTP operations
    • Added support for both API key and session token cookie authentication
    • Fixed cookie-based authentication in session token tests
  2. GetTracesByProjectResourceTest.java - Refactored endpoint calls

    • Refactored 8 instances of direct client.target(URL_TEMPLATE) calls
    • Simplified getAndAssertPage() method by using callGetTracesWithQueryParams()
    • Changed from building WebTarget conditionally to building a Map of query parameters
    • Replaced search endpoint calls with callSearchTracesStream()
    • Fixed time filtering test to use mutable HashMap instead of immutable Map.of()
  3. FindTraceThreadsResourceTest.java - New test file with TraceResourceClient usage

    • Added as part of the refactoring to test trace threads retrieval
    • Uses TraceResourceClient methods for all HTTP operations
    • Tests both API key and session token cookie authentication
  4. TraceResourceClient.java - Extended with new methods

    • Added 18+ new methods for encapsulating HTTP operations
    • Methods include: callGetTracesWithQueryParams(), callSearchTracesStream(), callGetWithPath(), callPutToPath(), callPostToPath(), callDeleteToPath(), callGetTraceThreadsWithSorting()
    • Cookie-based variants for session token authentication (_WithCookie methods)
    • Removed duplicate methods (callGetTraces, callSearchTraces)
    • Made getWebTarget() private to prevent direct access
    • Extracted addPathSegments() and addQueryParameters() helper methods to BaseCommentResourceClient
  5. SpanResourceClient.java - Added cookie authentication support

    • Added callGetSpansWithQueryParamsAndCookie() and callFeedbackScoresWithContainerAndCookie()
    • Extracted addQueryParameters() helper method to BaseCommentResourceClient
  6. BaseCommentResourceClient.java - New shared helper methods

    • Added addPathSegments() protected method for building path segments across multiple path parts
    • Added addQueryParameters() protected method for adding query parameters to WebTarget
    • Reduces code duplication between TraceResourceClient and SpanResourceClient
  7. Code Quality Improvements

    • Added missing HashMap import
    • Removed unused imports (Entity, WebTarget, HttpHeaders, WORKSPACE_HEADER)
    • All compilation errors resolved
    • Eliminated code duplication through helper methods

Change checklist

  • User facing
  • Documentation update

Issues

  • Resolves OPIK-2856

Testing

  • ✅ Backend compiles successfully (mvn clean compile)
  • ✅ All 83 tests in GetTracesByProjectResourceTest$FindTraces pass
  • ✅ Time filtering test whenTimeParametersInISO8601Format_thenReturnFilteredTraces passes
  • ✅ All TracesResourceTest tests pass with refactored resource client usage
  • ✅ No new regressions introduced

Documentation

No documentation updates needed for this refactoring. This is an internal test code improvement.

- Add InstantToUUIDMapper to convert Instant timestamps to UUIDv7 bounds
- Add InstantParamConverter to parse ISO-8601 and epoch millisecond time parameters
- Update TracesResource to accept from_time and to_time parameters on /traces and /traces/stats endpoints
- Update TraceDAO to apply UUID-based time filtering using BETWEEN clause on id column
- Update TraceSearchCriteria to include uuidFromTime and uuidToTime fields
- Add comprehensive integration tests for time filtering with boundary conditions
- All tests passing: 10/10 time filtering tests + validation tests
…d type safety

- Fix InstantParamConverter to catch specific DateTimeParseException instead of generic Exception
- Add debug logging when falling back to epoch milliseconds parsing
- Refactor anonymous ParamConverter class to named InstantConverter inner class for clarity
- Suppress unchecked cast with @SuppressWarnings annotation
- Fix MySQLContainerUtils return type to use MySQLContainer<?> for type safety
- Update tests to reflect that toUpperBound uses next millisecond (+1ms) for inclusive BETWEEN queries
- Remove outdated assertions expecting same timestamp in both bounds
- Verify upper bound is lexicographically greater than lower bound
- All 13 tests now passing
- #7: Add INSTANCE singleton pattern for InstantConverter
- #8: Use StringUtils.isEmpty() for null-safe empty check
- Note: #2 and #3 already addressed in previous commit
- Simplified InstantToUUIDMapper to use IdGenerator.getTimeOrderedEpoch() instead of convertOtelIdToUUIDv7
- Per UUIDv7 RFC, sub-millisecond 12 bits are optional with millisecond granularity
- Start/end interval semantics with ±1ms ensures correct BETWEEN query results
- This approach has been battle-tested for months without issues per reviewer recommendation
- Converted InstantToUUIDMapper to @singleton service for proper DI integration
- Updated TracesResource to inject InstantToUUIDMapper dependency
- Updated tests to properly mock IdGenerator dependency
…ce helper method and fix transformTestParams call
…stead of direct URL_TEMPLATE calls

- Replace all direct client.target(URL_TEMPLATE) calls with TraceResourceClient methods
- Add callFeedbackScoresWithCookie method to TraceResourceClient for session token authentication
- Add callRetrieveThreadResponseWithCookie method to TraceResourceClient for session token authentication
- Fix feedback batch endpoint by using callFeedbackScores and callFeedbackScoresWithCookie
- Add null checks for query parameters to prevent NPE errors
- Fix API key vs session token usage in authentication tests
- Rename get__whenApiKeyIsPresent__thenReturnTraceThread to get__whenSessionTokenIsPresent__thenReturnTraceThread in SessionTokenCookie class
- Add mockGetWorkspaceIdByName() calls for proper workspace mocking
- Preserve original test assertions and behavior
- All tests properly refactored to use resource client methods instead of direct HTTP calls
- Remove callGetTraces() - duplicate of callGetTracesWithQueryParams()
- Remove callSearchTraces() - duplicate of callSearchTracesStream()
- Reduced code duplication and maintenance burden
Copilot AI review requested due to automatic review settings November 5, 2025 13:20
@thiagohora thiagohora requested a review from a team as a code owner November 5, 2025 13:20
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR refactors test code to use TraceResourceClient and SpanResourceClient instead of direct HTTP client calls, improving maintainability and reducing code duplication. The main changes include extracting HTTP operations into reusable client methods, adding support for cookie-based authentication, and ensuring consistent API patterns across all test methods.

Key changes:

  • Centralized HTTP client operations in TraceResourceClient and SpanResourceClient with 18+ new helper methods
  • Replaced 8+ instances of direct client.target(URL_TEMPLATE) calls with client method invocations
  • Added cookie-based authentication support for session token testing

Reviewed Changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
TracesResourceTest.java Replaced direct HTTP calls with traceResourceClient methods; removed unused imports and fields
GetTracesByProjectResourceTest.java Refactored endpoint calls to use callGetTracesWithQueryParams() and callSearchTracesStream(); changed to HashMap for query params
FindTraceThreadsResourceTest.java New file extracting trace thread tests from TracesResourceTest.java
TraceResourceClient.java Added 18+ new methods for encapsulating HTTP operations with both API key and cookie authentication
SpanResourceClient.java Added cookie authentication support methods; added callGetSpansWithQueryParams()

@comet-ml comet-ml deleted a comment from github-actions bot Nov 5, 2025
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Nov 5, 2025

Backend Tests Results

  281 files    281 suites   53m 20s ⏱️
5 397 tests 5 389 ✅ 8 💤 0 ❌
5 352 runs  5 344 ✅ 8 💤 0 ❌

Results for commit 5be3b4a.

♻️ This comment has been updated with latest results.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Nov 5, 2025

SDK E2E Tests Results

0 tests   0 ✅  0s ⏱️
0 suites  0 💤
0 files    0 ❌

Results for commit 42a2556.

♻️ This comment has been updated with latest results.

@thiagohora thiagohora force-pushed the thiaghora/OPIK-2856-refactor-traces-resource-test-url-template branch from 42a2556 to 9c84962 Compare November 5, 2025 13:33
@thiagohora thiagohora merged commit 99aa306 into main Nov 5, 2025
16 checks passed
@thiagohora thiagohora deleted the thiaghora/OPIK-2856-refactor-traces-resource-test-url-template branch November 5, 2025 16:28
awkoy pushed a commit that referenced this pull request Nov 12, 2025
…d of direct URL_TEMPLATE calls (#3947)

* [NA] [BE] Upgrade MySQL container from Testcontainers

* Fix imports order

* [OPIK-2856] [BE] Implement UUIDv7 time-based filtering for traces

- Add InstantToUUIDMapper to convert Instant timestamps to UUIDv7 bounds
- Add InstantParamConverter to parse ISO-8601 and epoch millisecond time parameters
- Update TracesResource to accept from_time and to_time parameters on /traces and /traces/stats endpoints
- Update TraceDAO to apply UUID-based time filtering using BETWEEN clause on id column
- Update TraceSearchCriteria to include uuidFromTime and uuidToTime fields
- Add comprehensive integration tests for time filtering with boundary conditions
- All tests passing: 10/10 time filtering tests + validation tests

* [OPIK-2856] Address PR review comments: improve exception handling and type safety

- Fix InstantParamConverter to catch specific DateTimeParseException instead of generic Exception
- Add debug logging when falling back to epoch milliseconds parsing
- Refactor anonymous ParamConverter class to named InstantConverter inner class for clarity
- Suppress unchecked cast with @SuppressWarnings annotation
- Fix MySQLContainerUtils return type to use MySQLContainer<?> for type safety

* [OPIK-2856] Fix InstantToUUIDMapperTest to match implementation

- Update tests to reflect that toUpperBound uses next millisecond (+1ms) for inclusive BETWEEN queries
- Remove outdated assertions expecting same timestamp in both bounds
- Verify upper bound is lexicographically greater than lower bound
- All 13 tests now passing

* Remove setup duplicated code

* Revision 2: Address PR review comments - LOW priority fixes

- #7: Add INSTANCE singleton pattern for InstantConverter
- #8: Use StringUtils.isEmpty() for null-safe empty check
- Note: #2 and #3 already addressed in previous commit

* Revision 3: Use IdGenerator.getTimeOrderedEpoch() for UUID bounds

- Simplified InstantToUUIDMapper to use IdGenerator.getTimeOrderedEpoch() instead of convertOtelIdToUUIDv7
- Per UUIDv7 RFC, sub-millisecond 12 bits are optional with millisecond granularity
- Start/end interval semantics with ±1ms ensures correct BETWEEN query results
- This approach has been battle-tested for months without issues per reviewer recommendation
- Converted InstantToUUIDMapper to @singleton service for proper DI integration
- Updated TracesResource to inject InstantToUUIDMapper dependency
- Updated tests to properly mock IdGenerator dependency

* Fix tests

* [OPIK-2856] [BE] Split Get spans Tests

* Fix format

* Revision 2: Extract duplicated span creation logic into createSpanWithTimestamp helper method

* [OPIK-2856] [BE] Implement UUIDv7 time-based filtering for spans

* Revision 3: Extract workspace setup duplication into setupTestWorkspace helper method and fix transformTestParams call

* [OPIK-2856] Refactor TracesResourceTest to use TraceResourceClient instead of direct URL_TEMPLATE calls

- Replace all direct client.target(URL_TEMPLATE) calls with TraceResourceClient methods
- Add callFeedbackScoresWithCookie method to TraceResourceClient for session token authentication
- Add callRetrieveThreadResponseWithCookie method to TraceResourceClient for session token authentication
- Fix feedback batch endpoint by using callFeedbackScores and callFeedbackScoresWithCookie
- Add null checks for query parameters to prevent NPE errors
- Fix API key vs session token usage in authentication tests
- Rename get__whenApiKeyIsPresent__thenReturnTraceThread to get__whenSessionTokenIsPresent__thenReturnTraceThread in SessionTokenCookie class
- Add mockGetWorkspaceIdByName() calls for proper workspace mocking
- Preserve original test assertions and behavior
- All tests properly refactored to use resource client methods instead of direct HTTP calls

* [OPIK-2856] Remove duplicate methods from TraceResourceClient

- Remove callGetTraces() - duplicate of callGetTracesWithQueryParams()
- Remove callSearchTraces() - duplicate of callSearchTracesStream()
- Reduced code duplication and maintenance burden

* Fix tests

* Revision 2: Address Copilot review comments - remove redundant wrapper method and add clarifying comment

* Revision 3: Extract duplicated path splitting logic into helper method addPathSegments()

* Revision 4: Make getWebTarget() private and add callGetTraceThreadsWithSorting() public method

* Revision 7: Move addPathSegments() and addQueryParameters() helper methods to BaseCommentResourceClient
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.

3 participants