testing

package
v0.0.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 4, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

AuthSome Testing Package

A comprehensive testing package for developers building applications with AuthSome authentication. This package provides mocked services, helpers, and utilities to test your integration without requiring a full AuthSome setup.

✨ Version 2.0 - Now with full multi-tenancy support, core/contexts integration, and Forge HTTP handler testing.

Overview

The testing package allows you to:

  • Create mock users, organizations, apps, and environments
  • Simulate authenticated contexts with full multi-tenant hierarchy
  • Test authorization scenarios (roles, permissions)
  • Verify session handling and expiration
  • Test multi-tenancy scenarios across apps and environments
  • Use pre-configured common scenarios
  • Test HTTP handlers with mock Forge contexts

What's New in v2.0

  • Multi-Tenancy Support: Full App → Environment → Organization hierarchy
  • Core Contexts Integration: Uses AuthSome's actual context system from core/contexts
  • Forge HTTP Testing: Mock Forge contexts for testing HTTP handlers
  • Builder Pattern: Fluent API for creating complex test data
  • OrganizationService Mock: Complete organization service implementation
  • Updated API: All methods now use xid.ID instead of strings

Quick Start

import (
    "testing"
    authsometesting "github.com/xraph/authsome/testing"
)

func TestMyHandler(t *testing.T) {
    // Create a mock instance
    mock := authsometesting.NewMock(t)
    defer mock.Reset()

    // Quick setup: create authenticated context with full tenant hierarchy
    ctx := mock.NewTestContext()

    // Your test code here
    result := myHandler(ctx)
    // ... assertions
}

Core Components

Mock Instance

The Mock struct is the main entry point for testing. It provides:

  • Mock user, session, and organization services
  • In-memory storage for test data (Apps, Environments, Organizations, Users, Sessions)
  • Helper methods for creating test scenarios
  • Context manipulation utilities
  • Default entities (app, environment, organization) auto-created
mock := authsometesting.NewMock(t)
defer mock.Reset() // Clean up after tests

// Access default entities
defaultApp := mock.GetDefaultApp()
defaultEnv := mock.GetDefaultEnvironment()
defaultOrg := mock.GetDefaultOrg()
Multi-Tenancy Architecture

The testing framework mirrors AuthSome's multi-tenant architecture:

App (e.g., "My SaaS Platform")
  └── Environment (e.g., "production", "staging")
      └── Organization (e.g., "Acme Corp", "TechStart Inc")
          └── Users/Members

Every authenticated context includes:

  • App ID: Top-level tenant
  • Environment ID: Per-app environment
  • Organization ID: User-created workspace
  • User ID: Individual user

Creating Test Data

Simple Methods
Users
// Create a basic user (auto-added to default org)
user := mock.CreateUser("[email protected]", "Test User")

// Create a user with specific role
adminUser := mock.CreateUserWithRole("[email protected]", "Admin", "admin")

// Get user
user, err := mock.GetUser(userID)
Apps and Environments
// Get defaults (auto-created)
app := mock.GetDefaultApp()
env := mock.GetDefaultEnvironment()

// Access via getters
app, err := mock.GetApp(appID)
env, err := mock.GetEnvironment(envID)
Organizations
// Get default organization (auto-created)
org := mock.GetDefaultOrg()

// Create additional organization
org := mock.CreateOrganization("My Org", "my-org")

// Get organization
org, err := mock.GetOrganization(orgID)

// Add user to organization
member := mock.AddUserToOrg(userID, orgID, "member")

// Get user's organizations
orgs, err := mock.GetUserOrgs(userID)
Sessions
// Create active session
session := mock.CreateSession(userID, orgID)

// Create expired session (for testing expiration)
expiredSession := mock.CreateExpiredSession(userID, orgID)

// Get session
session, err := mock.GetSession(sessionID)
Builder Pattern (Fluent API)

For more complex test data creation:

// Build a custom app
app := mock.NewApp().
    WithName("Custom App").
    WithSlug("custom-app").
    Build()

// Build a custom environment
env := mock.NewEnvironment(app.ID).
    WithName("staging").
    WithSlug("staging").
    Build()

// Build a custom organization
org := mock.NewOrganization().
    WithName("Acme Corp").
    WithSlug("acme").
    WithApp(app.ID).
    WithEnvironment(env.ID).
    Build()

// Build a custom user
user := mock.NewUser().
    WithEmail("[email protected]").
    WithName("John Doe").
    WithRole("admin").
    WithEmailVerified(true).
    Build()

Working with Context

Creating Authenticated Contexts
// Method 1: Quick way - creates user, org, session with all tenant levels
ctx := mock.NewTestContext()

// Method 2: With specific user
user := mock.CreateUser("[email protected]", "Test User")
ctx := mock.NewTestContextWithUser(user)

// Method 3: Manual setup with full control
user := mock.CreateUser("[email protected]", "Test User")
session := mock.CreateSession(user.ID, mock.GetDefaultOrg().ID)
ctx := context.Background()
ctx = mock.WithApp(ctx, mock.GetDefaultApp().ID)
ctx = mock.WithEnvironment(ctx, mock.GetDefaultEnvironment().ID)
ctx = mock.WithOrganization(ctx, mock.GetDefaultOrg().ID)
ctx = mock.WithSession(ctx, session.ID)
Retrieving from Context

The testing package uses AuthSome's actual context system (core/contexts):

// Get user ID
userID, ok := authsometesting.GetUserID(ctx)
if !ok || userID.IsNil() {
    // Not authenticated
}

// Get app ID
appID, ok := authsometesting.GetAppID(ctx)

// Get environment ID
envID, ok := authsometesting.GetEnvironmentID(ctx)

// Get organization ID
orgID, ok := authsometesting.GetOrganizationID(ctx)

// Get session
session, ok := authsometesting.GetSession(ctx)

// Get full entities from context using Mock
user, err := mock.GetUserFromContext(ctx)
app, err := mock.GetAppFromContext(ctx)
env, err := mock.GetEnvironmentFromContext(ctx)
org, err := mock.GetOrganizationFromContext(ctx)

Authorization Helpers

// Require authentication
user, err := mock.RequireAuth(ctx)
if err != nil {
    // Handle: ErrNotAuthenticated, ErrInvalidSession, ErrUserNotFound, ErrUserInactive
}

// Require organization membership
member, err := mock.RequireOrgMember(ctx, orgID)
if err != nil {
    // Handle: ErrOrgNotFound, ErrNotOrgMember
}

// Require specific role
member, err := mock.RequireOrgRole(ctx, orgID, "admin")
if err != nil {
    // Handle: ErrInsufficientPermissions
}

Mock Services

UserService
// Create user
user, err := mock.UserService.Create(ctx, &user.CreateUserRequest{
    Email: "[email protected]",
    Name:  "Test User",
})

// Get user by ID
user, err := mock.UserService.GetByID(ctx, userID)

// Get user by email
user, err := mock.UserService.GetByEmail(ctx, "[email protected]")

// Update user
user, err := mock.UserService.Update(ctx, userID, &user.UpdateUserRequest{
    Name: &newName,
})

// Delete user
err := mock.UserService.Delete(ctx, userID)
SessionService
// Create session
session, err := mock.SessionService.Create(ctx, &session.CreateSessionRequest{
    UserID:         userID,
    OrganizationID: orgID,
})

// Get session by ID
session, err := mock.SessionService.GetByID(ctx, sessionID)

// Get session by token
session, err := mock.SessionService.GetByToken(ctx, token)

// Validate session
session, err := mock.SessionService.Validate(ctx, token)

// Delete session
err := mock.SessionService.Delete(ctx, sessionID)
OrganizationService
// Get organization by ID
org, err := mock.OrganizationService.GetByID(ctx, orgID)

// Get organization by slug
org, err := mock.OrganizationService.GetBySlug(ctx, "my-org")

// List organizations
orgsResp, err := mock.OrganizationService.ListOrganizations(ctx, filter)

// Get members
membersResp, err := mock.OrganizationService.GetMembers(ctx, orgID)

// Get user organizations
orgs, err := mock.OrganizationService.GetUserOrganizations(ctx, userID)

Testing HTTP Handlers

Mock Forge Contexts
import (
    "net/http"
    "net/http/httptest"
)

func TestHandler(t *testing.T) {
    mock := authsometesting.NewMock(t)
    defer mock.Reset()

    // Create test user
    user := mock.CreateUser("[email protected]", "Test User")

    // Quick authenticated Forge context
    forgeCtx := mock.QuickAuthenticatedForgeContext("GET", "/api/profile")

    // Or with specific user
    forgeCtx := mock.QuickAuthenticatedForgeContextWithUser("POST", "/api/data", user)

    // Or full control
    req := httptest.NewRequest("GET", "/api/profile", nil)
    session := mock.CreateSession(user.ID, mock.GetDefaultOrg().ID)
    forgeCtx := mock.MockAuthenticatedForgeContext(
        req,
        user,
        mock.GetDefaultApp(),
        mock.GetDefaultEnvironment(),
        mock.GetDefaultOrg(),
        session,
    )

    // Test your handler
    err := yourHandler.HandleProfile(forgeCtx)
    assert.NoError(t, err)
    assert.Equal(t, 200, forgeCtx.GetStatus())
}

Common Scenarios

Pre-configured scenarios for common testing needs:

scenarios := mock.CommonScenarios()

// Authenticated user
scenario := scenarios.AuthenticatedUser()
ctx := scenario.Context
user := scenario.User
app := scenario.App
env := scenario.Environment
org := scenario.Org

// Admin user
scenario := scenarios.AdminUser()

// Unverified user
scenario := scenarios.UnverifiedUser()

// Multi-org user
scenario := scenarios.MultiOrgUser()

// Expired session
scenario := scenarios.ExpiredSession()

// Unauthenticated (no auth data)
scenario := scenarios.UnauthenticatedUser()

// Inactive user (deleted/suspended)
scenario := scenarios.InactiveUser()

Each scenario includes:

  • Name: Scenario identifier
  • Description: What the scenario represents
  • User: Test user (if applicable)
  • App: Test app
  • Environment: Test environment
  • Org: Test organization
  • Session: Test session (if applicable)
  • Context: Pre-configured context

Complete Examples

Example 1: Testing User Profile Handler
func TestGetUserProfile(t *testing.T) {
    mock := authsometesting.NewMock(t)
    defer mock.Reset()

    // Create test data
    user := mock.CreateUser("[email protected]", "John Doe")
    ctx := mock.NewTestContextWithUser(user)

    // Test handler
    profile, err := getUserProfile(ctx, mock)

    // Assertions
    require.NoError(t, err)
    assert.Equal(t, "John Doe", profile.Name)
    assert.Equal(t, "[email protected]", profile.Email)
}
Example 2: Testing Multi-Org Scenario
func TestMultiOrgAccess(t *testing.T) {
    mock := authsometesting.NewMock(t)
    defer mock.Reset()

    // Create user and multiple orgs
    user := mock.CreateUser("[email protected]", "Test User")
    org1 := mock.GetDefaultOrg()
    org2 := mock.CreateOrganization("Second Org", "second-org")
    
    // Add user to second org as admin
    mock.AddUserToOrg(user.ID, org2.ID, "admin")

    // Test access to org1 (as member)
    ctx1 := context.Background()
    ctx1 = mock.WithApp(ctx1, mock.GetDefaultApp().ID)
    ctx1 = mock.WithEnvironment(ctx1, mock.GetDefaultEnvironment().ID)
    ctx1 = mock.WithOrganization(ctx1, org1.ID)
    ctx1 = mock.WithUser(ctx1, user.ID)
    
    member, err := mock.RequireOrgMember(ctx1, org1.ID)
    require.NoError(t, err)
    assert.Equal(t, "member", member.Role)

    // Test access to org2 (as admin)
    ctx2 := context.Background()
    ctx2 = mock.WithApp(ctx2, mock.GetDefaultApp().ID)
    ctx2 = mock.WithEnvironment(ctx2, mock.GetDefaultEnvironment().ID)
    ctx2 = mock.WithOrganization(ctx2, org2.ID)
    ctx2 = mock.WithUser(ctx2, user.ID)
    
    member, err = mock.RequireOrgRole(ctx2, org2.ID, "admin")
    require.NoError(t, err)
    assert.Equal(t, "admin", member.Role)
}
Example 3: Testing Session Expiration
func TestSessionExpiration(t *testing.T) {
    mock := authsometesting.NewMock(t)
    defer mock.Reset()

    user := mock.CreateUser("[email protected]", "Test User")
    expiredSession := mock.CreateExpiredSession(user.ID, mock.GetDefaultOrg().ID)

    // Try to use expired session
    _, err := mock.SessionService.Validate(context.Background(), expiredSession.Token)
    assert.Error(t, err)
    assert.Contains(t, err.Error(), "expired")
}
Example 4: Testing with Builder Pattern
func TestComplexScenario(t *testing.T) {
    mock := authsometesting.NewMock(t)
    defer mock.Reset()

    // Build custom app structure
    app := mock.NewApp().
        WithName("Production App").
        WithSlug("prod-app").
        Build()

    env := mock.NewEnvironment(app.ID).
        WithName("production").
        WithSlug("prod").
        Build()

    org := mock.NewOrganization().
        WithName("Enterprise Corp").
        WithSlug("enterprise").
        WithApp(app.ID).
        WithEnvironment(env.ID).
        Build()

    user := mock.NewUser().
        WithEmail("[email protected]").
        WithName("Jane Smith").
        WithRole("owner").
        Build()

    // Create context with all custom entities
    session := mock.CreateSession(user.ID, org.ID)
    ctx := context.Background()
    ctx = mock.WithApp(ctx, app.ID)
    ctx = mock.WithEnvironment(ctx, env.ID)
    ctx = mock.WithOrganization(ctx, org.ID)
    ctx = mock.WithSession(ctx, session.ID)

    // Test your application logic
    // ...
}

Error Constants

Common errors you can test against:

authsometesting.ErrNotAuthenticated      // User not authenticated
authsometesting.ErrInvalidSession        // Session invalid or expired
authsometesting.ErrUserNotFound          // User doesn't exist
authsometesting.ErrOrgNotFound          // Organization doesn't exist
authsometesting.ErrNotOrgMember         // User not member of org
authsometesting.ErrInsufficientPermissions // User lacks required permissions
authsometesting.ErrUserInactive         // User account inactive/deleted

Thread Safety

All Mock operations are thread-safe and can be used in concurrent tests:

func TestConcurrent(t *testing.T) {
    mock := authsometesting.NewMock(t)
    defer mock.Reset()

    t.Run("user1", func(t *testing.T) {
        t.Parallel()
        user := mock.CreateUser("[email protected]", "User 1")
        // ... test with user1
    })

    t.Run("user2", func(t *testing.T) {
        t.Parallel()
        user := mock.CreateUser("[email protected]", "User 2")
        // ... test with user2
    })
}

Best Practices

  1. Always call Reset(): Use defer mock.Reset() to ensure test isolation
  2. Use scenarios for common cases: Leverage CommonScenarios() for standard tests
  3. Test full hierarchy: When testing multi-tenancy, include App/Environment/Organization
  4. Use builders for complex data: Builder pattern makes complex test data readable
  5. Verify contexts: Always check context retrieval with ok return values
  6. Test error paths: Use error constants to test failure scenarios
  7. Parallel tests: Mock is thread-safe, use t.Parallel() where appropriate

Migration from v1.x

If you're upgrading from v1.x:

API Changes
// Old (v1.x)
user.ID.String()                       // String IDs
authsometesting.GetLoggedInUser(ctx)   // Old context helpers
mock.WithOrg(ctx, orgID)               // Old method name

// New (v2.0)
user.ID                                // xid.ID directly
authsometesting.GetUserID(ctx)         // New context helpers
mock.WithOrganization(ctx, orgID)      // New method name
New Features
  • App and Environment support
  • Builder pattern for test data
  • Forge context mocking
  • OrganizationService mock
  • Core contexts integration
Breaking Changes
  • All ID parameters now use xid.ID instead of string
  • Context helpers renamed to match core/contexts
  • WithOrg renamed to WithOrganization
  • Member storage now uses OrganizationMember schema

Support

For issues, questions, or contributions, please visit the AuthSome repository.

Documentation

Overview

Package testing provides comprehensive mocking utilities for testing applications that integrate with the AuthSome authentication framework.

Version 2.0: Now with full multi-tenancy support, core/contexts integration, and Forge HTTP handler testing.

Overview

This package is designed for external users who need to test their applications that depend on AuthSome without setting up a full AuthSome instance with database, Redis, and other infrastructure components.

Quick Start

Import the package and create a mock instance:

import (
    "testing"
    authsometesting "github.com/xraph/authsome/testing"
)

func TestMyHandler(t *testing.T) {
    mock := authsometesting.NewMock(t)
    defer mock.Reset()

    // Create authenticated context with full tenant hierarchy
    ctx := mock.NewTestContext()

    // Your test code here
}

Core Features

  • Multi-Tenancy: Full App → Environment → Organization hierarchy support
  • Core Contexts: Uses AuthSome's actual context system from core/contexts
  • Mock Users: Create test users with various states (verified, unverified, active, inactive)
  • Mock Sessions: Create active or expired sessions for testing authentication flows
  • Mock Organizations: Create organizations and manage memberships
  • Mock Services: UserService, SessionService, OrganizationService with full CRUD operations
  • Context Helpers: Easily add authentication data to context with typed keys
  • Common Scenarios: Pre-configured scenarios for typical test cases
  • Authorization Helpers: Test role-based access control
  • Forge Mocking: Mock Forge contexts for HTTP handler testing
  • Builder Pattern: Fluent API for creating complex test data
  • Thread-Safe: Safe for concurrent use in tests

Creating Test Data

Create users:

user := mock.CreateUser("[email protected]", "Test User")
adminUser := mock.CreateUserWithRole("[email protected]", "Admin", "admin")

Create sessions:

session := mock.CreateSession(user.ID, org.ID)
expiredSession := mock.CreateExpiredSession(user.ID, org.ID)

Create organizations:

org := mock.CreateOrganization("My Org", "my-org")
member := mock.AddUserToOrg(user.ID, org.ID, "member")

Working with Context

Create authenticated contexts:

// Quick way - creates user, org, and session automatically
ctx := mock.NewTestContext()

// With specific user
user := mock.CreateUser("[email protected]", "Test User")
ctx := mock.NewTestContextWithUser(user)

// Manual setup with full control
ctx := context.Background()
ctx = mock.WithApp(ctx, app.ID)
ctx = mock.WithEnvironment(ctx, env.ID)
ctx = mock.WithOrganization(ctx, org.ID)
ctx = mock.WithSession(ctx, session.ID)

Retrieve from context (using core/contexts):

userID, ok := authsometesting.GetUserID(ctx)
appID, ok := authsometesting.GetAppID(ctx)
envID, ok := authsometesting.GetEnvironmentID(ctx)
orgID, ok := authsometesting.GetOrganizationID(ctx)
session, ok := authsometesting.GetSession(ctx)

// Get full entities from context
user, err := mock.GetUserFromContext(ctx)
org, err := mock.GetOrganizationFromContext(ctx)

Authorization Testing

Test authentication and authorization:

// Require authentication
user, err := mock.RequireAuth(ctx)

// Require organization membership
member, err := mock.RequireOrgMember(ctx, orgID)

// Require specific role
member, err := mock.RequireOrgRole(ctx, orgID, "admin")

Common Scenarios

Use pre-configured scenarios for typical test cases:

scenarios := mock.NewCommonScenarios()

// Various scenarios available:
authUser := scenarios.AuthenticatedUser()
adminUser := scenarios.AdminUser()
unverifiedUser := scenarios.UnverifiedUser()
multiOrgUser := scenarios.MultiOrgUser()
expiredSession := scenarios.ExpiredSession()
unauthenticated := scenarios.UnauthenticatedUser()
inactiveUser := scenarios.InactiveUser()

// Use scenario in tests
user := authUser.User
ctx := authUser.Context

Service Methods

Test with mock services that implement the same interfaces as real services:

// User service
user, err := mock.UserService.GetByEmail(ctx, "[email protected]")
user, err := mock.UserService.GetByID(ctx, userID)
user, err := mock.UserService.Create(ctx, req)
user, err := mock.UserService.Update(ctx, userID, req)

// Session service
session, err := mock.SessionService.GetByToken(ctx, token)
session, err := mock.SessionService.Validate(ctx, token)
err := mock.SessionService.Delete(ctx, sessionID)

// Organization service
org, err := mock.OrganizationService.GetByID(ctx, orgID)
org, err := mock.OrganizationService.GetBySlug(ctx, "my-org")
membersResp, err := mock.OrganizationService.GetMembers(ctx, orgID)
orgs, err := mock.OrganizationService.GetUserOrganizations(ctx, userID)

Builder Pattern

Create complex test data with fluent API:

app := mock.NewApp().
    WithName("Production App").
    WithSlug("prod-app").
    Build()

user := mock.NewUser().
    WithEmail("[email protected]").
    WithName("Admin User").
    WithRole("admin").
    Build()

HTTP Handler Testing

Test HTTP handlers with mock Forge contexts:

// Quick authenticated context
forgeCtx := mock.QuickAuthenticatedForgeContext("GET", "/api/profile")

// With specific user
user := mock.CreateUser("[email protected]", "Test User")
forgeCtx := mock.QuickAuthenticatedForgeContextWithUser("POST", "/api/data", user)

// Full control
req := httptest.NewRequest("GET", "/api/profile", nil)
session := mock.CreateSession(user.ID, org.ID)
forgeCtx := mock.MockAuthenticatedForgeContext(req, user, app, env, org, session)

Complete Example

Here's a complete example testing a handler that requires authentication:

func TestGetUserProfile(t *testing.T) {
    mock := authsometesting.NewMock(t)
    defer mock.Reset()

    // Handler being tested
    getUserProfile := func(ctx context.Context, mock *authsometesting.Mock) (map[string]string, error) {
        userID, ok := authsometesting.GetUserID(ctx)
        if !ok || userID.IsNil() {
            return nil, authsometesting.ErrNotAuthenticated
        }
        user, err := mock.GetUserFromContext(ctx)
        if err != nil {
            return nil, err
        }
        return map[string]string{
            "id":    user.ID.String(),
            "email": user.Email,
            "name":  user.Name,
        }, nil
    }

    t.Run("authenticated", func(t *testing.T) {
        ctx := mock.NewTestContext()
        profile, err := getUserProfile(ctx, mock)
        require.NoError(t, err)
        assert.NotEmpty(t, profile["id"])
    })

    t.Run("unauthenticated", func(t *testing.T) {
        ctx := context.Background()
        _, err := getUserProfile(ctx, mock)
        assert.Equal(t, authsometesting.ErrNotAuthenticated, err)
    })
}

Migration from v1.x

Key changes in v2.0:

  • All ID parameters now use xid.ID instead of string
  • Context helpers renamed to match core/contexts (GetUserID vs GetLoggedInUser)
  • WithOrg renamed to WithOrganization
  • Added App and Environment support
  • Added builder pattern for test data creation
  • Added Forge context mocking
  • Member storage now uses OrganizationMember schema

Best Practices

  • Always call defer mock.Reset() to clean up between tests
  • Use common scenarios for typical test cases
  • Test both success and failure cases
  • Use table-driven tests for multiple scenarios
  • Verify context values before using them (check ok return values)
  • Test full tenant hierarchy (App/Environment/Organization) for multi-tenant features
  • Use builder pattern for complex test data
  • Leverage Forge mocking for HTTP handler tests

Thread Safety

The mock implementation is thread-safe and can be used across multiple goroutines in your tests.

Limitations

This is a testing mock and does not:

  • Connect to a real database
  • Implement full RBAC policy evaluation
  • Support all AuthSome plugins
  • Provide rate limiting or caching
  • Validate complex business logic

For integration testing with real services, use the full AuthSome setup.

See the README.md file in this package for more detailed documentation and examples.

Package testing provides mocked Authsome instances and utilities for testing external integrations with the authsome authentication framework.

This package is designed for developers building applications that integrate with authsome and need to test their code without setting up a full authsome instance with database, Redis, etc.

Example usage:

import (
    "testing"
    authsometesting "github.com/xraph/authsome/testing"
)

func TestMyHandler(t *testing.T) {
    // Create a mock authsome with a test user
    mock := authsometesting.NewMock(t)
    user := mock.CreateUser("[email protected]", "Test User")
    org := mock.GetDefaultOrg()
    session := mock.CreateSession(user.ID.String(), org.ID.String())

    // Set up authenticated context
    ctx := mock.WithSession(context.Background(), session.ID.String())

    // Your test code here
    result, err := myService.DoSomething(ctx)
    // ... assertions
}

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotAuthenticated        = &TestError{Code: "not_authenticated", Message: "user is not authenticated"}
	ErrInvalidSession          = &TestError{Code: "invalid_session", Message: "session is invalid or expired"}
	ErrUserNotFound            = &TestError{Code: "user_not_found", Message: "user not found"}
	ErrUserInactive            = &TestError{Code: "user_inactive", Message: "user account is inactive"}
	ErrOrgNotFound             = &TestError{Code: "org_not_found", Message: "organization not found"}
	ErrNotOrgMember            = &TestError{Code: "not_org_member", Message: "user is not a member of this organization"}
	ErrInsufficientPermissions = &TestError{Code: "insufficient_permissions", Message: "user does not have required permissions"}
)

Common test errors

Functions

func GetAppID

func GetAppID(ctx context.Context) (xid.ID, bool)

GetAppID retrieves the app ID from context using core/contexts

func GetEnvironmentID

func GetEnvironmentID(ctx context.Context) (xid.ID, bool)

GetEnvironmentID retrieves the environment ID from context using core/contexts

func GetOrganizationID

func GetOrganizationID(ctx context.Context) (xid.ID, bool)

GetOrganizationID retrieves the organization ID from context using core/contexts

func GetSession

func GetSession(ctx context.Context) (*schema.Session, bool)

GetSession retrieves the session object from context

func GetUserID

func GetUserID(ctx context.Context) (xid.ID, bool)

GetUserID retrieves the user ID from context using core/contexts

Types

type AppBuilder

type AppBuilder struct {
	// contains filtered or unexported fields
}

AppBuilder helps create test apps with fluent API

func (*AppBuilder) Build

func (b *AppBuilder) Build() *schema.App

Build saves the app and returns it

func (*AppBuilder) WithName

func (b *AppBuilder) WithName(name string) *AppBuilder

WithName sets the app name

func (*AppBuilder) WithSlug

func (b *AppBuilder) WithSlug(slug string) *AppBuilder

WithSlug sets the app slug

type CommonScenarios

type CommonScenarios struct {
	// contains filtered or unexported fields
}

CommonScenarios provides pre-configured test scenarios.

func (*CommonScenarios) AdminUser

func (cs *CommonScenarios) AdminUser() *Scenario

AdminUser returns a scenario with an admin user.

func (*CommonScenarios) AuthenticatedUser

func (cs *CommonScenarios) AuthenticatedUser() *Scenario

AuthenticatedUser returns a scenario with a basic authenticated user.

func (*CommonScenarios) ExpiredSession

func (cs *CommonScenarios) ExpiredSession() *Scenario

ExpiredSession returns a scenario with an expired session.

func (*CommonScenarios) InactiveUser

func (cs *CommonScenarios) InactiveUser() *Scenario

InactiveUser returns a scenario with an inactive user account.

func (*CommonScenarios) MultiOrgUser

func (cs *CommonScenarios) MultiOrgUser() *Scenario

MultiOrgUser returns a scenario with a user belonging to multiple organizations.

func (*CommonScenarios) UnauthenticatedUser

func (cs *CommonScenarios) UnauthenticatedUser() *Scenario

UnauthenticatedUser returns a scenario with no authentication.

func (*CommonScenarios) UnverifiedUser

func (cs *CommonScenarios) UnverifiedUser() *Scenario

UnverifiedUser returns a scenario with an unverified user.

type EnvironmentBuilder

type EnvironmentBuilder struct {
	// contains filtered or unexported fields
}

EnvironmentBuilder helps create test environments with fluent API

func (*EnvironmentBuilder) Build

Build saves the environment and returns it

func (*EnvironmentBuilder) WithName

func (b *EnvironmentBuilder) WithName(name string) *EnvironmentBuilder

WithName sets the environment name

func (*EnvironmentBuilder) WithSlug

func (b *EnvironmentBuilder) WithSlug(slug string) *EnvironmentBuilder

WithSlug sets the environment slug

type Mock

type Mock struct {

	// Core services
	UserService         *MockUserService
	SessionService      *MockSessionService
	OrganizationService *MockOrganizationService
	// contains filtered or unexported fields
}

Mock provides a mocked Authsome instance for testing.

func NewMock

func NewMock(t *testing.T) *Mock

NewMock creates a new mock Authsome instance for testing. It automatically creates default app, environment, and organization.

func (*Mock) AddUserToOrg

func (m *Mock) AddUserToOrg(userID, orgID xid.ID, role string) *schema.OrganizationMember

AddUserToOrg adds a user to an organization with the specified role.

func (*Mock) CreateExpiredSession

func (m *Mock) CreateExpiredSession(userID, orgID xid.ID) *schema.Session

CreateExpiredSession creates an expired session for testing expiration scenarios.

func (*Mock) CreateOrganization

func (m *Mock) CreateOrganization(name, slug string) *schema.Organization

CreateOrganization creates a test organization.

func (*Mock) CreateSession

func (m *Mock) CreateSession(userID, orgID xid.ID) *schema.Session

CreateSession creates a test session for the given user and organization.

func (*Mock) CreateUser

func (m *Mock) CreateUser(email, name string) *schema.User

CreateUser creates a test user with the given email and name. The user is automatically added to the default organization.

func (*Mock) CreateUserWithRole

func (m *Mock) CreateUserWithRole(email, name, role string) *schema.User

CreateUserWithRole creates a test user with a specific role in the default organization.

func (*Mock) GetApp

func (m *Mock) GetApp(appID xid.ID) (*schema.App, error)

GetApp retrieves an app by ID.

func (*Mock) GetAppFromContext

func (m *Mock) GetAppFromContext(ctx context.Context) (*schema.App, error)

GetAppFromContext retrieves the full app object from context using the Mock

func (*Mock) GetDefaultApp

func (m *Mock) GetDefaultApp() *schema.App

GetDefaultApp returns the default test app.

func (*Mock) GetDefaultEnvironment

func (m *Mock) GetDefaultEnvironment() *schema.Environment

GetDefaultEnvironment returns the default test environment.

func (*Mock) GetDefaultOrg

func (m *Mock) GetDefaultOrg() *schema.Organization

GetDefaultOrg returns the default test organization.

func (*Mock) GetEnvironment

func (m *Mock) GetEnvironment(envID xid.ID) (*schema.Environment, error)

GetEnvironment retrieves an environment by ID.

func (*Mock) GetEnvironmentFromContext

func (m *Mock) GetEnvironmentFromContext(ctx context.Context) (*schema.Environment, error)

GetEnvironmentFromContext retrieves the full environment object from context using the Mock

func (*Mock) GetOrganization

func (m *Mock) GetOrganization(orgID xid.ID) (*schema.Organization, error)

GetOrganization retrieves an organization by ID.

func (*Mock) GetOrganizationFromContext

func (m *Mock) GetOrganizationFromContext(ctx context.Context) (*schema.Organization, error)

GetOrganizationFromContext retrieves the full organization object from context using the Mock

func (*Mock) GetSession

func (m *Mock) GetSession(sessionID xid.ID) (*schema.Session, error)

GetSession retrieves a session by ID.

func (*Mock) GetUser

func (m *Mock) GetUser(userID xid.ID) (*schema.User, error)

GetUser retrieves a user by ID.

func (*Mock) GetUserFromContext

func (m *Mock) GetUserFromContext(ctx context.Context) (*schema.User, error)

GetUserFromContext retrieves the full user object from context using the Mock

func (*Mock) GetUserOrgs

func (m *Mock) GetUserOrgs(userID xid.ID) ([]*schema.Organization, error)

GetUserOrgs returns all organizations a user is a member of.

func (*Mock) MockAuthenticatedForgeContext

func (m *Mock) MockAuthenticatedForgeContext(
	req *http.Request,
	user *schema.User,
	app *schema.App,
	env *schema.Environment,
	org *schema.Organization,
	session *schema.Session,
) *MockForgeContext

MockAuthenticatedForgeContext creates an authenticated mock Forge context This is useful for testing HTTP handlers that require authentication

func (*Mock) NewApp

func (m *Mock) NewApp() *AppBuilder

NewApp creates a new AppBuilder

func (*Mock) NewCommonScenarios

func (m *Mock) NewCommonScenarios() *CommonScenarios

NewCommonScenarios creates a new set of common test scenarios.

func (*Mock) NewEnvironment

func (m *Mock) NewEnvironment(appID xid.ID) *EnvironmentBuilder

NewEnvironment creates a new EnvironmentBuilder

func (*Mock) NewMockForgeContext

func (m *Mock) NewMockForgeContext(req *http.Request) *MockForgeContext

NewMockForgeContext creates a basic mock forge context for testing

func (*Mock) NewOrganization

func (m *Mock) NewOrganization() *OrganizationBuilder

NewOrganization creates a new OrganizationBuilder

func (*Mock) NewTestContext

func (m *Mock) NewTestContext() context.Context

NewTestContext creates fully authenticated context with all tenancy levels

func (*Mock) NewTestContextWithUser

func (m *Mock) NewTestContextWithUser(user *schema.User) context.Context

NewTestContextWithUser creates authenticated context for specific user

func (*Mock) NewUser

func (m *Mock) NewUser() *UserBuilder

NewUser creates a new UserBuilder

func (*Mock) QuickAuthenticatedForgeContext

func (m *Mock) QuickAuthenticatedForgeContext(method, path string) *MockForgeContext

QuickAuthenticatedForgeContext creates authenticated Forge context with defaults This is the simplest way to create an authenticated context for testing

func (*Mock) QuickAuthenticatedForgeContextWithUser

func (m *Mock) QuickAuthenticatedForgeContextWithUser(method, path string, user *schema.User) *MockForgeContext

QuickAuthenticatedForgeContextWithUser creates authenticated Forge context for specific user

func (*Mock) QuickForgeContext

func (m *Mock) QuickForgeContext(method, path string) *MockForgeContext

QuickForgeContext creates a basic unauthenticated Forge context

func (*Mock) RequireAuth

func (m *Mock) RequireAuth(ctx context.Context) (*schema.User, error)

RequireAuth is a helper that mimics authentication middleware behavior. It checks if the context has a valid session and returns the user.

func (*Mock) RequireOrgMember

func (m *Mock) RequireOrgMember(ctx context.Context, orgID xid.ID) (*schema.OrganizationMember, error)

RequireOrgMember checks if the user is a member of the specified organization.

func (*Mock) RequireOrgRole

func (m *Mock) RequireOrgRole(ctx context.Context, orgID xid.ID, requiredRole string) (*schema.OrganizationMember, error)

RequireOrgRole checks if the user has the specified role in the organization.

func (*Mock) Reset

func (m *Mock) Reset()

Reset clears all test data. Useful for cleanup between tests.

func (*Mock) WithApp

func (m *Mock) WithApp(ctx context.Context, appID xid.ID) context.Context

WithApp sets app in context using core/contexts

func (*Mock) WithEnvironment

func (m *Mock) WithEnvironment(ctx context.Context, envID xid.ID) context.Context

WithEnvironment sets environment in context using core/contexts

func (*Mock) WithOrganization

func (m *Mock) WithOrganization(ctx context.Context, orgID xid.ID) context.Context

WithOrganization sets organization in context using core/contexts

func (*Mock) WithSession

func (m *Mock) WithSession(ctx context.Context, sessionID xid.ID) context.Context

WithSession adds session and user to context

func (*Mock) WithUser

func (m *Mock) WithUser(ctx context.Context, userID xid.ID) context.Context

WithUser sets user in context using core/contexts

type MockForgeContext

type MockForgeContext struct {
	// contains filtered or unexported fields
}

MockForgeContext is a mock implementation of forge.Context for testing

func (*MockForgeContext) BindJSON

func (c *MockForgeContext) BindJSON(v interface{}) error

func (*MockForgeContext) Cookie

func (c *MockForgeContext) Cookie(name string) (string, error)

func (*MockForgeContext) GetBody

func (c *MockForgeContext) GetBody() interface{}

func (*MockForgeContext) GetStatus

func (c *MockForgeContext) GetStatus() int

func (*MockForgeContext) HTML

func (c *MockForgeContext) HTML(status int, html string) error

func (*MockForgeContext) Header

func (c *MockForgeContext) Header() http.Header

func (*MockForgeContext) JSON

func (c *MockForgeContext) JSON(status int, data interface{}) error

func (*MockForgeContext) Param

func (c *MockForgeContext) Param(name string) string

func (*MockForgeContext) Query

func (c *MockForgeContext) Query(key string) string

func (*MockForgeContext) Redirect

func (c *MockForgeContext) Redirect(status int, url string) error

func (*MockForgeContext) Request

func (c *MockForgeContext) Request() *http.Request

func (*MockForgeContext) Response

func (c *MockForgeContext) Response() http.ResponseWriter

func (*MockForgeContext) SetHeader

func (c *MockForgeContext) SetHeader(key, value string)

func (*MockForgeContext) SetParam

func (c *MockForgeContext) SetParam(name, value string)

func (*MockForgeContext) String

func (c *MockForgeContext) String(status int, s string) error

type MockOrganizationService

type MockOrganizationService struct {
	// contains filtered or unexported fields
}

MockOrganizationService implements organization service methods for testing.

func (*MockOrganizationService) AddMember

func (s *MockOrganizationService) AddMember(ctx context.Context, orgID, userID xid.ID, role string) (*organization.Member, error)

AddMember adds a user as a member to an organization

func (*MockOrganizationService) CreateOrganization

func (s *MockOrganizationService) CreateOrganization(ctx context.Context, req *organization.CreateOrganizationRequest, creatorUserID, appID, environmentID xid.ID) (*organization.Organization, error)

CreateOrganization creates a new organization

func (*MockOrganizationService) FindOrganizationByID

func (s *MockOrganizationService) FindOrganizationByID(ctx context.Context, id xid.ID) (*organization.Organization, error)

FindOrganizationByID retrieves an organization by ID

func (*MockOrganizationService) FindOrganizationBySlug

func (s *MockOrganizationService) FindOrganizationBySlug(ctx context.Context, appID, environmentID xid.ID, slug string) (*organization.Organization, error)

FindOrganizationBySlug retrieves an organization by slug

func (*MockOrganizationService) GetByID

GetByID is an alias for FindOrganizationByID for compatibility

func (*MockOrganizationService) GetBySlug

GetBySlug is an alias for FindOrganizationBySlug for compatibility

func (*MockOrganizationService) GetMembers

GetMembers is an alias for ListMembers for compatibility

func (*MockOrganizationService) GetUserMemberships

GetUserMemberships retrieves all memberships for a user

func (*MockOrganizationService) GetUserOrganizations

func (s *MockOrganizationService) GetUserOrganizations(ctx context.Context, userID xid.ID) ([]*organization.Organization, error)

GetUserOrganizations retrieves all organizations a user is a member of

func (*MockOrganizationService) ListMembers

ListMembers lists members of an organization

func (*MockOrganizationService) ListOrganizations

ListOrganizations lists organizations with pagination

type MockSessionService

type MockSessionService struct {
	// contains filtered or unexported fields
}

MockSessionService implements core session service methods for testing.

func (*MockSessionService) Create

func (*MockSessionService) Delete

func (s *MockSessionService) Delete(ctx context.Context, sessionID xid.ID) error

func (*MockSessionService) GetByID

func (s *MockSessionService) GetByID(ctx context.Context, sessionID xid.ID) (*schema.Session, error)

func (*MockSessionService) GetByToken

func (s *MockSessionService) GetByToken(ctx context.Context, token string) (*schema.Session, error)

func (*MockSessionService) Validate

func (s *MockSessionService) Validate(ctx context.Context, token string) (*schema.Session, error)

type MockUserService

type MockUserService struct {
	// contains filtered or unexported fields
}

MockUserService implements core user service methods for testing.

func (*MockUserService) Create

func (*MockUserService) Delete

func (s *MockUserService) Delete(ctx context.Context, userID xid.ID) error

func (*MockUserService) GetByEmail

func (s *MockUserService) GetByEmail(ctx context.Context, email string) (*schema.User, error)

func (*MockUserService) GetByID

func (s *MockUserService) GetByID(ctx context.Context, userID xid.ID) (*schema.User, error)

func (*MockUserService) Update

func (s *MockUserService) Update(ctx context.Context, userID xid.ID, req *user.UpdateUserRequest) (*schema.User, error)

type OrganizationBuilder

type OrganizationBuilder struct {
	// contains filtered or unexported fields
}

OrganizationBuilder helps create test organizations with fluent API

func (*OrganizationBuilder) Build

Build saves the organization and returns it

func (*OrganizationBuilder) WithApp

func (b *OrganizationBuilder) WithApp(appID xid.ID) *OrganizationBuilder

WithApp sets the app ID

func (*OrganizationBuilder) WithEnvironment

func (b *OrganizationBuilder) WithEnvironment(envID xid.ID) *OrganizationBuilder

WithEnvironment sets the environment ID

func (*OrganizationBuilder) WithMetadata

func (b *OrganizationBuilder) WithMetadata(metadata map[string]interface{}) *OrganizationBuilder

WithMetadata sets metadata

func (*OrganizationBuilder) WithName

func (b *OrganizationBuilder) WithName(name string) *OrganizationBuilder

WithName sets the organization name

func (*OrganizationBuilder) WithSlug

func (b *OrganizationBuilder) WithSlug(slug string) *OrganizationBuilder

WithSlug sets the organization slug

type Scenario

type Scenario struct {
	Name        string
	Description string
	User        *schema.User
	App         *schema.App
	Environment *schema.Environment
	Org         *schema.Organization
	Session     *schema.Session
	Context     context.Context
}

Scenario represents a common test scenario with pre-configured data.

type TestError

type TestError struct {
	Code    string
	Message string
}

TestError represents a test error with a code and message.

func (*TestError) Error

func (e *TestError) Error() string

type UserBuilder

type UserBuilder struct {
	// contains filtered or unexported fields
}

UserBuilder helps create test users with fluent API

func (*UserBuilder) Build

func (b *UserBuilder) Build() *schema.User

Build saves the user and returns it

func (*UserBuilder) WithEmail

func (b *UserBuilder) WithEmail(email string) *UserBuilder

WithEmail sets the user email

func (*UserBuilder) WithEmailVerified

func (b *UserBuilder) WithEmailVerified(verified bool) *UserBuilder

WithEmailVerified sets email verification status

func (*UserBuilder) WithName

func (b *UserBuilder) WithName(name string) *UserBuilder

WithName sets the user name

func (*UserBuilder) WithRole

func (b *UserBuilder) WithRole(role string) *UserBuilder

WithRole sets the role for the default organization

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL