VOOZH about

URL: https://deepwiki.com/hypervel/foundation/6.7-authentication-and-session-testing

⇱ Authentication and Session Testing | hypervel/foundation | DeepWiki


Loading...
Last indexed: 7 February 2026 (101eff)
Menu

Authentication and Session Testing

This page documents the authentication and session testing utilities provided by the InteractsWithAuthentication and InteractsWithSession traits in Hypervel Foundation's testing infrastructure.

For general testing infrastructure, see page 6.1. For HTTP request testing that utilizes these utilities, see page 6.3. For test response assertions, see page 6.4.

Overview

The authentication and session testing system consists of two trait-based concerns:

TraitPurpose
InteractsWithAuthenticationSet authenticated users and assert authentication state
InteractsWithSessionManipulate session data and lifecycle

Both traits are composed into the TestCase base class, making their methods available to all tests. These utilities integrate with the MakesHttpRequests trait for HTTP testing and the TestResponse class for response assertions.

Sources: src/Testing/TestCase.php10-31 src/Testing/Concerns/InteractsWithAuthentication.php1-137 src/Testing/Concerns/InteractsWithSession.php1-67

Authentication Testing

Setting Authenticated Users

The InteractsWithAuthentication trait provides actingAs() and be() methods to set the authenticated user without performing login.

Authentication Flow


Method Signatures

MethodSignatureReturns
actingAs()actingAs(UserContract $user, ?string $guard = null): staticFluent interface
be()be(UserContract $user, ?string $guard = null): staticFluent interface

Implementation Details

  1. actingAs() is an alias for be()
  2. be() resets the wasRecentlyCreated flag if present to prevent side effects
  3. Retrieves AuthFactoryContract from the application container
  4. Calls guard($guard)->setUser($user) to set the authenticated user
  5. Calls shouldUse($guard) to make the guard active
  6. Returns $this for method chaining

Sources: src/Testing/Concerns/InteractsWithAuthentication.php12-37

Authentication Assertions

The trait provides assertion methods to verify authentication state.

Assertion Methods

MethodSignatureAssertion
assertAuthenticated()assertAuthenticated(?string $guard = null): staticUser is authenticated
assertGuest()assertGuest(?string $guard = null): staticUser is not authenticated
assertAuthenticatedAs()assertAuthenticatedAs(UserContract $user, ?string $guard = null): staticSpecific user is authenticated

Authentication Check Flow


Implementation

  • isAuthenticated() helper method calls guard()->check() to determine authentication state
  • assertAuthenticatedAs() retrieves the current user via guard()->user() and compares:
    • Instance type using assertInstanceOf()
    • Authentication identifier using assertSame()

Sources: src/Testing/Concerns/InteractsWithAuthentication.php39-95

Credential Validation Assertions

The trait provides methods to test credential validity without performing authentication.

Credential Assertion Methods

MethodSignatureAssertion
assertCredentials()assertCredentials(array $credentials, ?string $guard = null): staticCredentials are valid
assertInvalidCredentials()assertInvalidCredentials(array $credentials, ?string $guard = null): staticCredentials are invalid

Credential Validation Flow


Implementation

The hasCredentials() protected method:

  1. Retrieves the UserProvider from the guard via getProvider()
  2. Calls retrieveByCredentials() to find the user
  3. If user exists, calls validateCredentials() to check password
  4. Returns boolean indicating credential validity

This validates credentials without modifying authentication state.

Sources: src/Testing/Concerns/InteractsWithAuthentication.php97-136

Session Testing

Setting Session Data

The InteractsWithSession trait provides methods to populate and manage session data in tests.

Session Methods

MethodSignaturePurpose
withSession()withSession(array $data): staticAlias for session()
session()session(array $data): staticSet session key-value pairs
startSession()startSession(): staticEnsure session is started
flushSession()flushSession(): staticClear all session data

Session Initialization Flow


Session Lifecycle

The startSession() method mimics the behavior of the StartSession middleware:

  1. Retrieves the Session instance from the container
  2. Checks if session is already started via isStarted()
  3. If not started and no session ID exists, generates one via setId(null)
  4. Calls start() to initialize the session

This ensures session data persists across HTTP requests in tests.

Sources: src/Testing/Concerns/InteractsWithSession.php1-67

Session Lifecycle in Tests

Session State Transitions


Lifecycle States

StateDescriptionKey Methods
UnstartedSession instance exists but not initializedN/A
ID GenerationSession ID created if none existssession->setId(null)
StartedSession is active and readysession->start()
Data PopulatedKey-value pairs storedsession->put()
Request MadeHTTP request with session access$this->get()
Assert StateVerify session contentsassertSessionHas()
FlushedSession data clearedsession->flush()

Sources: src/Testing/Concerns/InteractsWithSession.php24-66

Session Assertions on Test Responses

The TestResponse class provides comprehensive assertion methods for validating session state after HTTP requests.

Basic Session Assertions

Session Presence and Value Assertions

Assertion MethodParametersPurpose
assertSessionHas()array|string $key, mixed $value = nullAssert session has key, optionally with value
assertSessionHasAll()array $bindingsAssert session has multiple key-value pairs
assertSessionMissing()array|string $keyAssert session key does not exist

Value Comparison Options

When calling assertSessionHas() with a value parameter:

  • Null: Only checks key existence
  • Closure: Passes session value to closure, asserts closure returns truthy
  • Scalar/Array: Uses strict equality comparison

Sources: src/Testing/Http/TestResponse.php239-275

Flashed Input Assertions

Session flash data, particularly old input, can be tested with dedicated assertion methods.

Flashed Input Methods


The assertSessionHasInput() method validates flashed input data using the session's hasOldInput() and getOldInput() methods, which retrieve input data that was flashed during the previous request (typically after validation failures).

Sources: src/Testing/Http/TestResponse.php277-308

Validation Error Assertions

The testing framework provides robust validation error assertion methods that integrate with Laravel-style validation error bags.

Error Assertion Methods

MethodParametersPurpose
assertSessionHasErrors()array|string $keys, mixed $format, string $errorBagAssert validation errors exist
assertSessionHasErrorsIn()string $errorBag, array $keys, mixed $formatAssert errors in specific bag
assertSessionHasNoErrors()NoneAssert no validation errors exist
assertSessionDoesntHaveErrors()array|string $keys, ?string $format, string $errorBagAssert specific errors absent

Error Bag System

Validation errors are stored in a ViewErrorBag instance in the session under the errors key. The error bag can contain multiple named message bags (default is 'default'). Each message bag contains field-specific error messages.

Empty Keys Behavior

Calling assertSessionDoesntHaveErrors() with an empty keys array invokes assertSessionHasNoErrors(), which comprehensively checks that no errors exist in any bag.

Sources: src/Testing/Http/TestResponse.php310-398

Session Debugging

The TestResponse class provides debugging methods for inspecting session state.

Debugging Methods

MethodDescription
dumpSession()Dumps all session data using dump()

This method calls session()->all() to retrieve all session data and passes it to the dump() helper function.

Sources: src/Testing/Http/TestResponse.php459-467

Integration with HTTP Testing

Complete Testing Workflow

Authentication and session utilities integrate with MakesHttpRequests and TestResponse for end-to-end testing.

Request Testing Flow


Typical Test Pattern


Sources: src/Testing/TestCase.php26-31 src/Testing/Concerns/MakesHttpRequests.php148-170 src/Testing/Concerns/InteractsWithAuthentication.php src/Testing/Concerns/InteractsWithSession.php

Session Access in TestResponse

TestResponse Session Integration


Session Resolution

The TestResponse class accesses the session via:

  1. Retrieves container from ApplicationContext::getContainer()
  2. Resolves Session::class from container
  3. Throws RuntimeException if hypervel/session package not installed

All session assertion methods internally call session() to access the current session instance.

Sources: src/Testing/Http/TestResponse.php228-236

Authentication Guards

All authentication methods accept an optional $guard parameter for multi-guard applications.

Guard Resolution

Guard Parameter Handling


Guard Usage

Method CallGuard UsedDescription
actingAs($user)Default guardUses auth.defaults.guard config
actingAs($user, 'web')web guardUses web guard explicitly
assertAuthenticated('api')api guardChecks API guard state
assertGuest('admin')admin guardChecks admin guard is guest

Multi-Guard Example


Sources: src/Testing/Concerns/InteractsWithAuthentication.php15-68

TestCase Trait Composition

The TestCase base class composes authentication and session testing traits alongside other testing concerns.


The trait-based architecture ensures all test methods have immediate access to authentication, session, HTTP, and container utilities without requiring manual trait inclusion.

Sources: src/Testing/TestCase.php24-33