Skip to content

Conversation

@lobehubbot
Copy link
Member

@lobehubbot lobehubbot commented Jan 8, 2026

Summary

  • Added comprehensive unit tests for NextAuthUserService
  • Total test files added: 1
  • Test cases added: 42
  • Coverage focus: NextAuth adapter implementation including user management, session handling, account linking, and authenticator operations

Changes

  • All tests pass successfully
  • Business logic coverage improved
  • Edge cases and error handling covered
  • Tests follow existing patterns

Module Processed

src/server/services/nextAuthUser/

Test Coverage

Functions tested:

  • User Management (7 tests):

    • createUser - user creation with duplicate detection by email and providerAccountId
    • getUser - user retrieval by ID
    • getUserByEmail - user retrieval with email validation
    • getUserByAccount - user retrieval via provider account
    • updateUser - user updates with error handling
    • deleteUser - user deletion with validation
  • Session Management (4 tests):

    • createSession - session creation
    • getSessionAndUser - session retrieval with user join
    • updateSession - session updates
    • deleteSession - session deletion
  • Account Management (4 tests):

    • linkAccount - account linking with error handling
    • unlinkAccount - account unlinking
    • getAccount - account retrieval
  • Authenticator Operations (5 tests):

    • createAuthenticator - authenticator creation
    • getAuthenticator - single authenticator retrieval with error handling
    • listAuthenticatorsByUserId - authenticator list retrieval
    • updateAuthenticatorCounter - counter updates with error handling
  • Verification Tokens (2 tests):

    • createVerificationToken - token creation
    • useVerificationToken - token consumption and deletion
  • Webhook Handlers (4 tests):

    • safeUpdateUser - safe user updates via provider webhooks
    • safeSignOutUser - safe sign-out via provider webhooks

Coverage type:

Unit tests with comprehensive mocking

Test approach:

  • Follows existing service testing patterns in the codebase
  • Uses Vitest with vi.mock for dependencies
  • Tests happy paths, edge cases, and error scenarios
  • Validates duplicate detection logic
  • Tests email validation (empty, whitespace)
  • Covers provider account ID fallback logic
  • Tests webhook warning scenarios for missing users

🤖 Generated with Claude Code

Summary by Sourcery

Add comprehensive unit tests for the NextAuthUserService covering its NextAuth adapter behavior.

Tests:

  • Add a new Vitest suite for NextAuthUserService covering user CRUD, email validation, and providerAccountId fallback logic.
  • Exercise session lifecycle operations including creation, retrieval with joined user, update, and deletion.
  • Cover account linking, unlinking, retrieval, and error handling when account persistence fails.
  • Test authenticator creation, lookup, listing by user, counter updates, and related failure paths.
  • Verify creation and consumption of verification tokens including null-return behavior when tokens are missing.
  • Validate webhook-safe user update and sign-out handlers, including logging when target users cannot be found.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
@vercel
Copy link

vercel bot commented Jan 8, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
lobehub Ready Ready Preview, Comment Jan 8, 2026 5:58am

@dosubot dosubot bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jan 8, 2026
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Jan 8, 2026

Reviewer's Guide

Adds a comprehensive Vitest unit test suite for NextAuthUserService, using a fully mocked LobeChatDatabase, UserModel, and logger to validate user, session, account, authenticator, verification-token operations and webhook-safe handlers across happy paths and failure scenarios.

Sequence diagram for safeUpdateUser webhook handler in NextAuthUserService

sequenceDiagram
  actor ProviderWebhook
  participant NextAuthUserService
  participant LobeChatDatabase
  participant UserModel
  participant Logger

  ProviderWebhook->>NextAuthUserService: safeUpdateUser(accountKey, updateData)
  NextAuthUserService->>Logger: info("nextauth safeUpdateUser: updating user")
  NextAuthUserService->>LobeChatDatabase: select().from(users).innerJoin(nextauthAccounts).where(accountKey)
  LobeChatDatabase-->>NextAuthUserService: userWithAccountRows
  alt user found
    NextAuthUserService->>UserModel: updateUser(updateData)
    UserModel-->>NextAuthUserService: updatedUser
    NextAuthUserService-->>ProviderWebhook: { status: 200, body: updatedUser }
  else user not found
    NextAuthUserService->>Logger: warn("nextauth safeUpdateUser: no user was found")
    NextAuthUserService-->>ProviderWebhook: { status: 200, body: null }
  end
Loading

Class diagram for NextAuthUserService and its mocked collaborators

classDiagram
  class NextAuthUserService {
    - LobeChatDatabase db
    + NextAuthUserService(db)
    + createUser(adapterUser)
    + getUser(userId)
    + getUserByEmail(email)
    + getUserByAccount(account)
    + updateUser(adapterUser)
    + deleteUser(userId)
    + createSession(sessionData)
    + getSessionAndUser(sessionToken)
    + updateSession(sessionData)
    + deleteSession(sessionToken)
    + linkAccount(account)
    + unlinkAccount(accountKey)
    + getAccount(providerAccountId, provider)
    + createAuthenticator(authenticatorData)
    + getAuthenticator(credentialID)
    + listAuthenticatorsByUserId(userId)
    + updateAuthenticatorCounter(credentialID, counter)
    + createVerificationToken(tokenData)
    + useVerificationToken(tokenKey)
    + safeUpdateUser(accountKey, updateData)
    + safeSignOutUser(accountKey)
  }

  class LobeChatDatabase {
    + select()
    + insert()
    + update()
    + delete()
  }

  class UserModel {
    + findById(db, userId)
    + findByEmail(db, email)
    + createUser(db, userData)
    + deleteUser(db, userId)
    + updateUser(updateData)
  }

  class Logger {
    + info(message)
    + warn(message)
  }

  class nextauthAccounts {
  }

  class nextauthSessions {
  }

  class nextauthAuthenticators {
  }

  class nextauthVerificationTokens {
  }

  class users {
  }

  NextAuthUserService --> LobeChatDatabase : uses
  NextAuthUserService --> UserModel : uses
  NextAuthUserService --> Logger : logs
  LobeChatDatabase --> nextauthAccounts : table
  LobeChatDatabase --> nextauthSessions : table
  LobeChatDatabase --> nextauthAuthenticators : table
  LobeChatDatabase --> nextauthVerificationTokens : table
  LobeChatDatabase --> users : table
Loading

Flow diagram for createUser logic in NextAuthUserService

flowchart TD
  A["createUser(adapterUser)"] --> B{"email is non-empty and not whitespace?"}
  B -- No --> C{"adapterUser.providerAccountId exists?"}
  B -- Yes --> D["UserModel.findByEmail(db, email)"]
  D --> E{"user found by email?"}
  E -- Yes --> F["return mapped existing user"]
  E -- No --> C

  C -- Yes --> G["UserModel.findById(db, providerAccountId)"]
  G --> H{"user found by providerAccountId?"}
  H -- Yes --> I["return mapped existing user"]
  H -- No --> J["use providerAccountId as new user id"]

  C -- No --> K["use adapterUser.id as new user id"]

  J --> L
  K --> L
  L["UserModel.createUser(db, newUserData)"] --> M["return mapped created user"]
Loading

File-Level Changes

Change Details Files
Add comprehensive unit tests for NextAuthUserService covering all major adapter operations and webhook-safe helpers.
  • Create a Vitest test suite that instantiates NextAuthUserService with a chainable mocked LobeChatDatabase implementation for select/insert/update/delete flows.
  • Mock UserModel static and instance methods (findById, findByEmail, createUser, deleteUser, updateUser) plus the pino logger, and define reusable mock adapter and domain user fixtures.
  • Cover createUser, getUser, getUserByEmail, getUserByAccount, updateUser, deleteUser behaviours including duplicate detection, providerAccountId fallback, and email empty/whitespace handling.
  • Test session CRUD (createSession, getSessionAndUser, updateSession, deleteSession) using tailored DB mocks that exercise joins and returning clauses.
  • Test account management (linkAccount, unlinkAccount, getAccount) including error cases when inserts return no rows.
  • Test WebAuthn authenticator APIs (createAuthenticator, getAuthenticator, listAuthenticatorsByUserId, updateAuthenticatorCounter) including error conditions when no rows are returned.
  • Test verification-token operations (createVerificationToken, useVerificationToken) for both success and token-not-found paths.
  • Test webhook helper methods safeUpdateUser and safeSignOutUser to assert logging behaviour on both “user found” and “user not found” paths and that sessions are deleted on sign out.
src/server/services/nextAuthUser/index.test.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@gru-agent
Copy link
Contributor

gru-agent bot commented Jan 8, 2026

TestGru Assignment

Summary

Link CommitId Status Reason
Detail de6c3ba 🚫 Skipped No files need to be tested {"src/server/services/nextAuthUser/index.test.ts":"File path does not match include patterns."}

History Assignment

Tip

You can @gru-agent and leave your feedback. TestGru will make adjustments based on your input

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +6 to +13
import {
UserItem,
nextauthAccounts,
nextauthAuthenticators,
nextauthSessions,
nextauthVerificationTokens,
users,
} from '@/database/schemas';
@arvinxx arvinxx closed this Jan 10, 2026
@arvinxx arvinxx deleted the automatic/add-tests-nextAuthUser-2026-01-08 branch February 8, 2026 15:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants