8000 GitHub - inflextion/netframework
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

inflextion/netframework

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

18 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

.NET Test Automation Framework

Sponsored by coffee β˜•, AI πŸ€–, and bench πŸ’Ί

A comprehensive test automation framework built with .NET 9 for API, UI, and database testing. Designed with clean architecture principles and follows industry best practices for maintainable and scalable test automation.

πŸš€ Features

  • Multi-Layer Testing: API, UI, and Database test support with integrated analytics testing
  • Cross-Browser Testing: Playwright integration with Chrome, Firefox, Safari, and Edge
  • Modern Page Object Model: Dual approaches with selector-based constants and ILocator patterns
  • Advanced API Testing: RestSharp-based HTTP client with factory pattern and analytics integration
  • Database Testing: Entity Framework Core 9.0 with SQL Server and In-Memory providers
  • Professional Reporting: Comprehensive Allure system with automated archiving and history preservation
  • Report Management: Professional scripts for archiving, cleaning, and serving reports
  • Playwright Tracing: Built-in trace capture for visual debugging and test analysis
  • Thread-Safe Logging: TestLogger with per-class file logging and console output
  • Static Configuration: Simple ConfigManager for direct configuration access without DI complexity
  • Fake Test Data: Bogus library integration for realistic test data generation
  • Developer Tooling: Enhanced Playwright codegen and trace viewer integration
  • CI/CD Ready: GitHub Actions and Azure DevOps pipeline examples
  • Clean Architecture: Layered design with clear separation of concerns
  • Cross-Platform Scripts: Separate Windows and Unix/Mac script versions

πŸ—οΈ Architecture

Design Patterns

  • Page Object Model for UI test organization (dual approach: selector-based and ILocator)
  • Repository Pattern for data access abstraction
  • Builder Pattern for test data and request construction
  • Factory Pattern for API clients and database initialization
  • Template Method for base test classes

SOLID Principles

  • βœ… Single Responsibility: Each class has a focused purpose
  • βœ… Open/Closed: Extensible base classes without modification
  • βœ… Liskov Substitution: Proper inheritance hierarchies
  • βœ… Interface Segregation: Focused interfaces where needed
  • βœ… Dependency Inversion: Abstractions over concrete implementations

πŸ› οΈ Technologies

Category Technology Version Purpose
Framework .NET 9.0 Core platform
Testing xUnit 2.9.3 Test runner and assertions
UI Automation Playwright 1.52.0 Cross-browser automation
API Testing RestSharp 112.1.0 HTTP client and requests
Database Entity Framework Core 9.0.5 ORM and database testing
Logging Serilog 4.3.0 Structured logging
Reporting Allure 2.12.1 Test reporting and analytics
Configuration Microsoft.Extensions.Configuration 9.0 Settings management
Test Data Bogus 35.6.3 Fake test data generation
Mocking AutoFixture.AutoMoq 4.18.1 Mock object generation

πŸ“ Project Structure

β”œβ”€β”€ API/                           # API Testing Layer
β”‚   β”œβ”€β”€ Builders/                  # Request builders (Fluent API)
β”‚   β”‚   └── ProductRequestBuilder.cs
β”‚   β”œβ”€β”€ Clients/                   # HTTP client wrappers
β”‚   β”‚   β”œβ”€β”€ ApiClientFactory.cs    # Factory for creating API clients
β”‚   β”‚   β”œβ”€β”€ AnalyticsClient.cs     # Analytics API client (new)
β”‚   β”‚   β”œβ”€β”€ BaseClient.cs          # Base HTTP client with common operations
β”‚   β”‚   └── ProductApiClient.cs    # Product-specific API client
β”‚   β”œβ”€β”€ Fixtures/                  # xUnit test fixtures
β”‚   β”‚   β”œβ”€β”€ ApiTestFixture.cs
β”‚   β”‚   └── DefaultApiTestFixture.cs
β”‚   └── Models/                    # API request/response models
β”‚       β”œβ”€β”€ AnalyticsResponse.cs   # Analytics data structure (new)
β”‚       β”œβ”€β”€ MergedProduct.cs       # Product merger operations (new)
β”‚       β”œβ”€β”€ Product.cs             # Base product model (new)
β”‚       β”œβ”€β”€ ProductRequest.cs      # Product request model (refactored)
β”‚       └── TopProduct.cs          # Product with quantity tracking (new)
β”‚
β”œβ”€β”€ Core/                          # Cross-cutting Concerns
β”‚   β”œβ”€β”€ Config/                    # Configuration management
β”‚   β”‚   └── ConfigManager.cs       # Static configuration manager
β”‚   β”œβ”€β”€ Enums/                     # Framework enumerations
β”‚   β”‚   β”œβ”€β”€ ApiClientType.cs       # API client type enumeration (updated)
β”‚   β”‚   └── BrowserList.cs
β”‚   β”œβ”€β”€ Logging/                   # Logging utilities
β”‚   β”‚   └── TestLogger.cs          # Thread-safe test logging (enhanced)
β”‚   β”œβ”€β”€ Models/                    # Framework models
β”‚   β”‚   β”œβ”€β”€ BaseModel.cs
β”‚   β”‚   └── PlaywrightSettings.cs  # Enhanced with tracing support
β”‚   └── Utils/                     # Helper utilities
β”‚       β”œβ”€β”€ FileUtils.cs           # File operations and utilities (new)
β”‚       β”œβ”€β”€ JsonHelper.cs
β”‚       └── TestDataFaker.cs       # Fake test data generation (updated)
β”‚
β”œβ”€β”€ Data/                          # Data Access Layer
β”‚   β”œβ”€β”€ DatabaseContext/           # Database context management
β”‚   β”‚   β”œβ”€β”€ DbContextFactory.cs
β”‚   β”‚   └── TestDbContext.cs       # Updated for new entity structure
β”‚   β”œβ”€β”€ Models/                    # Entity models
β”‚   β”‚   β”œβ”€β”€ ProductEntity.cs       # Renamed from Product.cs (new)
β”‚   β”‚   └── User.cs
β”‚   └── Repositories/              # Data access repositories
β”‚       β”œβ”€β”€ IProductRepository.cs  # Updated for ProductEntity
β”‚       β”œβ”€β”€ IUserRepository.cs
β”‚       β”œβ”€β”€ ProductRepository.cs   # Updated for ProductEntity
β”‚       └── UserRepository.cs
β”‚
β”œβ”€β”€ Tests/                         # Test Implementation
β”‚   β”œβ”€β”€ Base/                      # Base test classes (restructured)
β”‚   β”‚   β”œβ”€β”€ API/                   # API test base classes
β”‚   β”‚   β”‚   β”œβ”€β”€ AnalyticsBase.cs   # Analytics API test base (new)
β”‚   β”‚   β”‚   β”œβ”€β”€ BaseApiTest.cs     # Generic API test base
β”‚   β”‚   β”‚   └── ProductApiTestBase.cs # Product-specific API test base
β”‚   β”‚   └── UI/                    # UI test base classes
β”‚   β”‚       β”œβ”€β”€ BaseUiTest.cs      # Enhanced with tracing support
β”‚   β”‚       └── DynamicBrowser.cs  # Dynamic browser management (new)
β”‚   β”œβ”€β”€ Helpers/                   # Test helper utilities
β”‚   β”‚   β”œβ”€β”€ AllureHelper.cs        # Enhanced with better attachments
β”‚   β”‚   β”œβ”€β”€ DatabaseTestHelper.cs  # Updated for new entity structure
β”‚   β”‚   └── ScreenshotHelper.cs    # Enhanced screenshot capture (new)
β”‚   β”œβ”€β”€ Tests.API/                 # API test implementations
β”‚   β”‚   β”œβ”€β”€ AnalyticsTest.cs       # Analytics API tests (new)
β”‚   β”‚   └── ProductApiTests.cs     # Product API test cases
β”‚   β”œβ”€β”€ Tests.Mocks/               # Mock and test data providers
β”‚   β”‚   β”œβ”€β”€ BaseMockProvider.cs
β”‚   β”‚   └── ProductServiceTest.cs
β”‚   └── Tests.UI/                  # UI test implementations
β”‚       β”œβ”€β”€ AdvancedPageTests.cs   # Advanced UI interactions
β”‚       β”œβ”€β”€ BaseUrlLaunchTest.cs   # Cross-browser smoke tests
β”‚       └── LoginToProductPage.cs  # End-to-end user flow (new)
β”‚
β”œβ”€β”€ UI/                            # UI Testing Layer
β”‚   β”œβ”€β”€ Pages/                     # Page Object Models (dual approach)
β”‚   β”‚   β”œβ”€β”€ AdvancedWebElementsPage.cs # Advanced interactions using selectors
β”‚   β”‚   β”œβ”€β”€ BasePage.cs            # Base page with common functionality
β”‚   β”‚   β”œβ”€β”€ BasePageILocator.cs    # ILocator-based base page (new)
β”‚   β”‚   β”œβ”€β”€ IBasePage.cs           # Base page interface contract (new)
β”‚   β”‚   β”œβ”€β”€ LoginPage.cs           # Login page with ILocator pattern (new)
β”‚   β”‚   β”œβ”€β”€ UserPage.cs            # User page with complex interactions (new)
β”‚   β”‚   └── WebElementsPage.cs     # Basic page with selector constants
β”‚   └── PlaywrightSetup/           # Browser initialization
β”‚       └── PlaywrightSetup.cs     # Enhanced with tracing integration
β”‚
β”œβ”€β”€ Documentation/                 # Project documentation
β”‚   β”œβ”€β”€ design-patterns.md         # Architecture patterns guide
β”‚   β”œβ”€β”€ from-java-cheatsheet.md   # Java to .NET transition guide
β”‚   β”œβ”€β”€ playwright-getby-methods.md # Modern Playwright selector guide (new)
β”‚   β”œβ”€β”€ playwright-selectors-cheatsheet.md # Comprehensive selector reference
β”‚   └── workshop-program.md       # Training workshop materials
β”‚
β”œβ”€β”€ reports/                      # Test Execution Reports System
β”‚   β”œβ”€β”€ allure-results/           # Live test results and history
β”‚   β”œβ”€β”€ archive/                  # Archived reports with metadata
β”‚   └── scripts/                  # Report management utilities
β”‚       β”œβ”€β”€ archive-reports.ps1   # Archive reports with build info (Windows)
β”‚       β”œβ”€β”€ archive-reports-unix.ps1 # Archive reports (Unix/Mac)
β”‚       β”œβ”€β”€ clean-reports.ps1     # Clean reports (preserve history) (Windows)
β”‚       β”œβ”€β”€ clean-reports-unix.ps1 # Clean reports (Unix/Mac)
β”‚       β”œβ”€β”€ list-archives.ps1     # List and examine archives (Windows)
β”‚       β”œβ”€β”€ list-archives-unix.ps1 # List archives (Unix/Mac)
β”‚       β”œβ”€β”€ open-report.ps1       # Serve reports via web server (Windows)
β”‚       └── open-report-unix.ps1  # Serve reports (Unix/Mac)
β”‚
β”œβ”€β”€ allureConfig.json             # Allure reporting configuration
β”œβ”€β”€ codegen-unix.ps1              # Enhanced Playwright codegen tool (cross-platform)
β”œβ”€β”€ netframework.sln              # Visual Studio solution file (new)
β”œβ”€β”€ run-allure-tests.ps1         # Main test execution script (Windows)
β”œβ”€β”€ run-allure-tests-unix.ps1    # Main test execution script (Unix/Mac)
β”œβ”€β”€ testsettings.runsettings     # XUnit parallel execution settings
β”œβ”€β”€ trace-viewer.ps1             # Playwright trace viewer tool (new)
└── trace-viewer-unix.ps1        # Cross-platform trace viewer (new)

πŸ–₯️ Cross-Platform Support

The framework provides separate execution scripts for Windows and Unix-based systems (macOS, Linux):

Windows Scripts

  • run-allure-tests.ps1 - Main test execution
  • reports/scripts/*.ps1 - Report management scripts

Unix/Mac/Linux Scripts

  • run-allure-tests-unix.ps1 - Main test execution
  • reports/scripts/*-unix.ps1 - Report management scripts
  • codegen-unix.ps1 - Enhanced Playwright codegen
  • trace-viewer-unix.ps1 - Cross-platform trace viewer

The Unix scripts use forward slashes for paths and Unix-specific commands for optimal compatibility.

βš™οΈ Setup

Prerequisites

  • .NET 9 SDK or later
  • PowerShell (for cross-platform script execution)
  • Visual Studio 2022 or JetBrains Rider (recommended)
  • SQL Server LocalDB (for database tests)

Installation

  1. Clone the repository

    git clone <repository-url>
    cd netframework
  2. Restore packages

    dotnet restore
  3. Install Playwright browsers

    pwsh bin/Debug/net9.0/playwright.ps1 install
  4. Setup database (optional)

    dotnet ef database update

πŸ”§ Configuration

appsettings.json

{
  "Playwright": {
    "BrowserType": "Firefox",
    "Headless": false,
    "BaseUrl": "http://localhost:3000/",
    "BaseApiHost": "http://localhost:5001",
    "DefaultTimeoutMs": 30000,
    "ViewportWidth": 1280,
    "ViewportHeight": 800,
    "SlowMoMs": 1000,
    "EnableTracing": true
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TestDb_Tests;Trusted_Connection=true;"
  },
  "ApiClient": {
    "TimeoutMs": 30000,
    "RetryAttempts": 3
  },
  "TestApiSettings": {
    "BaseUrl": "http://localhost:5001"
  }
}

Environment Overrides

  • Create appsettings.Development.json for local settings
  • Use environment variables: Playwright__BrowserType=Chrome
  • Toggle tracing: Playwright__EnableTracing=true

πŸ§ͺ Running Tests

Quick Test Execution

# Windows
.\run-allure-tests.ps1

# Unix/Mac/Linux
pwsh ./run-allure-tests-unix.ps1

# This will:
# 1. Clean old results while preserving history
# 2. Run smoke tests (filter Category=Smoke)
# 3. Generate fresh Allure report
# 4. Start web server on http://localhost:5000

Specific Test Categories

# API Tests only
dotnet test --filter Category=API

# UI Tests only
dotnet test --filter Category=UI

# Database Tests only
dotnet test --filter Category=Database

# Smoke tests for CI/CD
dotnet test --filter Category=Smoke

Cross-Browser Testing

# Override browser via environment
$env:Playwright__BrowserType="Chrome"; dotnet test
$env:Playwright__BrowserType="Safari"; dotnet test
$env:Playwright__Headless="true"; dotnet test

Tracing Control

# Enable tracing globally
$env:Playwright__EnableTracing="true"; dotnet test

# Disable tracing
$env:Playwright__EnableTracing="false"; dotnet test

# View traces after test execution (Windows)
pwsh ./trace-viewer.ps1 -List
pwsh ./trace-viewer.ps1 TestClassName-trace

# View traces after test execution (Unix/Mac)
pwsh ./trace-viewer-unix.ps1 -List
pwsh ./trace-viewer-unix.ps1 TestClassName-trace

Parallel Execution

# Use optimized test settings (4 concurrent threads)
dotnet test --settings testsettings.runsettings

πŸ› οΈ Developer Tools

Playwright Codegen (Enhanced)

# Basic usage
pwsh ./codegen-unix.ps1

# With specific URL and browser
pwsh ./codegen-unix.ps1 -Url https://example.com -Browser firefox

# Mobile testing
pwsh ./codegen-unix.ps1 -Device "iPhone 12"

# With authentication state
pwsh ./codegen-unix.ps1 -LoadStorage auth.json -SaveStorage new-auth.json

# Show help for all options
pwsh ./codegen-unix.ps1 -Help

Trace Viewer (New)

# Windows
# List available traces
pwsh ./trace-viewer.ps1 -List

# Open specific trace
pwsh ./trace-viewer.ps1 BaseUrlLaunchTest-trace

# Show help
pwsh ./trace-viewer.ps1 -Help

# Unix/Mac
# List available traces
pwsh ./trace-viewer-unix.ps1 -List

# Open specific trace
pwsh ./trace-viewer-unix.ps1 BaseUrlLaunchTest-trace

# Show help
pwsh ./trace-viewer-unix.ps1 -Help

Test Development Workflow

  1. Generate initial test: Use pwsh ./codegen-unix.ps1 to record actions
  2. Transform to test: Convert codegen output to BaseUiTest pattern
  3. Add assertions: Use Page Object Model and proper assertions
  4. Run locally: Use pwsh ./run-allure-tests-unix.ps1 for full workflow
  5. Debug with traces: Use pwsh ./trace-viewer.ps1 (Windows) or pwsh ./trace-viewer-unix.ps1 (Unix/Mac) for visual debugging
  6. Review reports: Check results and screenshots in Allure

πŸ“ Writing Tests

API Test Example (Analytics)

public class AnalyticsTest : AnalyticsBase
{
    public AnalyticsTest(ITestOutputHelper output) : base(output) { }

    [Fact]
    public async Task GetAnalytics_GetRawAsync()
    {
        // Arrange
        var caseLogger = TestLogger.Logger.ForContext("TestMethod", nameof(GetAnalytics_GetRawAsync));
        caseLogger.Information("Sending GET request to /api/analytics");

        // Act - Using GetRawAsync for JSON manipulation
        var analyticsData = await Client.GetRawAsync("/api/analytics");
        AllureHelper.AttachString("Response Body", analyticsData.Content, "application/json", ".json");

        // Deserialize and work with JSON
        JObject analyticsJson = JsonHelper.Deserialize<JObject>(analyticsData.Content);
        JToken topProducts = analyticsJson["topProducts"];
        var topProductsList = topProducts.ToObject<List<TopProduct>>();

        // Assert
        Assert.NotNull(topProductsList);
        Assert.NotEmpty(topProductsList);
        
        var topProduct = topProductsList.OrderByDescending(p => p.Quantity).First();
        caseLogger.Information($"Top Product: {topProduct.Name} (Quantity: {topProduct.Quantity})");
    }

    [Fact]
    public async Task GetAnalytics_GetTypedAsync()
    {
        // Arrange
        var caseLogger = TestLogger.Logger.ForContext("TestMethod", nameof(GetAnalytics_GetTypedAsync));

        // Act - Using strongly typed response
        var analyticsData = await Client.GetAsync<AnalyticsResponse>("/api/analytics");
        AllureHelper.AttachString("Response Body", JsonHelper.Serialize(analyticsData), "application/json", ".json");

        // Assert
        Assert.NotNull(analyticsData);
        Assert.NotEmpty(analyticsData.TopProducts);

        // LINQ usage with strongly typed model
        var topProduct = analyticsData.TopProducts.OrderByDescending(p => p.Quantity).First();
        caseLogger.Information($"Top Product: {topProduct.Name} (Quantity: {topProduct.Quantity})");
    }
}

UI Test Example (Modern Page Objects)

public class LoginToProductPage : BaseUiTest
{
    public LoginToProductPage(ITestOutputHelper output) : base(output) { }

    [Fact]
    public async Task LoginToProduct()
    {
        // Arrange - Using ILocator-based page objects
        var loginPage = new LoginPage(Page, _settings, TestLogger.Logger);
        var productPage = new UserPage(Page, _settings, TestLogger.Logger);

        // Act
        await loginPage.Login("user", "user");
        await Expect(Page.Locator("h1")).ToHaveTextAsync("Welcome, user");

        var productList = await productPage.ReturnProducts();
        
        // Assert
        Assert.Contains("Acer Predator Helios 300", productList.Keys);
    }

    [Theory]
    [InlineData(BrowserList.Edge)]
    [InlineData(BrowserList.Firefox)]
    [InlineData(BrowserList.Webkit)]
    public async Task Should_Launch_BaseUrl(BrowserList browserType)
    {
        // Arrange - Cross-browser testing with tracing
        var caseLogger = TestLogger.Logger.ForContext("Browser", browserType)
                                         .ForContext("TestMethod", nameof(Should_Launch_BaseUrl));
        
        // Launch browser with tracing enabled
        await LaunchBrowserAsync(browserType, recordVideo: true, enableTracing: true);
        var webElements = new WebElementsPage(Page, _settings, caseLogger);

        // Act
        await webElements.GoToAsync("/webelements");
        await TakeScreenshotAsync($"After navigating to : {Page.Url}");
        await webElements.EnterTextInputAsync("my first text");
        await TakeScreenshotAsync("After Input");

        // Assert - using BasePage assertion methods
        await webElements.AssertOutputContains(".web-element:has(#text-input) .web-element-output", "my first text");
        webElements.AssertUrlContains(_settings.BaseUrl);
    }
}

Database Test Example (Updated Entities)

[Fact]
public async Task Should_Save_User_To_Database()
{
    // Arrange - Using fake test data
    var user = DatabaseTestHelper.CreateFakeUser();

    // Act
    var savedUser = DatabaseTestHelper.GetUserByEmail(user.Email);

    // Assert
    Assert.NotNull(savedUser);
    Assert.Equal(user.Name, savedUser.Name);
    Assert.Equal(user.Email, savedUser.Email);
}

[Fact]
public async Task Should_Create_Multiple_Fake_Products()
{
    // Arrange - Create multiple ProductEntity instances with varied fake data
    var products = new List<ProductEntity>();
    for (int i = 0; i < 5; i++)
    {
        products.Add(DatabaseTestHelper.CreateFakeProduct());
    }

    // Act
    var activeProducts = DatabaseTestHelper.GetActiveProducts();

    // Assert
    Assert.True(activeProducts.Count >= 5);
    Assert.All(activeProducts, p => Assert.True(p.Price > 0));
}

πŸ“Š Report Management

Quick Start with Reports

# Windows
.\run-allure-tests.ps1

# Unix/Mac/Linux
pwsh ./run-allure-tests-unix.ps1

# This will:
# 1. Clean old results while preserving history
# 2. Run smoke tests (filter Category=Smoke)
# 3. Generate fresh Allure report
# 4. Start web server on http://localhost:5000

Report Management Scripts

# Windows
.\reports\scripts\archive-reports.ps1 -BuildNumber "v1.2.3" -Branch "main"
.\reports\scripts\clean-reports.ps1
.\reports\scripts\list-archives.ps1 -Detailed
.\reports\scripts\open-report.ps1

# Unix/Mac/Linux
pwsh ./reports/scripts/archive-reports-unix.ps1 -BuildNumber "v1.2.3" -Branch "main"
pwsh ./reports/scripts/clean-reports-unix.ps1
pwsh ./reports/scripts/list-archives-unix.ps1 -Detailed
pwsh ./reports/scripts/open-report-unix.ps1

Advanced Allure Features

  • Custom Categories: Automatic classification of test failures
    • Infrastructure problems (driver/browser issues)
    • Product defects (application failures)
    • Test defects (test code issues)
    • Outdated tests (missing dependencies)
  • History Preservation: Trends and history maintained across runs
  • Rich Attachments: Screenshots, logs, API responses, and traces
  • Environment Reporting: Browser, platform, and framework metadata
  • Parallel Execution: Optimized for 4 concurrent threads

🎭 Modern Page Object Model

Dual Approach Support

The framework supports two modern Page Object Model approaches:

1. Selector-Based with BasePage Integration (Recommended for simple pages)

public class WebElementsPage : BasePage
{
    // Selectors as constants for maintainability
    private const string TextInputSelector = "#text-input";
    private const string TextInputOutputSelector = ".web-element:has(#text-input) .web-element-output";

    public WebElementsPage(IPage page, PlaywrightSettings settings, ILogger logger) 
        : base(page, settings, logger) { }

    // Methods use BasePage for consistent error handling
    public async Task EnterTextInputAsync(string text) =>
        await FillAsync(TextInputSelector, text);

    public async Task<string> GetTextInputOutputAsync() =>
        await InnerTextAsync(TextInputOutputSelector);
}

2. ILocator-Based with BasePageILocator (Recommended for complex pages)

public class LoginPage : BasePageILocator
{
    // ILocators for modern Playwright patterns
    public ILocator UsernameInput => Page.Locator("#username");
    public ILocator PasswordInput => Page.Locator("#password");
    public ILocator LoginButton => Page.GetByRole(AriaRole.Button, new() { Name = "Log in" });

    public LoginPage(IPage page, PlaywrightSettings settings, ILogger logger) 
        : base(page, settings, logger) { }

    public async Task Login(string username, string password)
    {
        await UsernameInput.FillAsync(username);
        await PasswordInput.FillAsync(password);
        await LoginButton.ClickAsync();
    }
}

πŸ” Key Architectural Changes

Recent Updates (2024)

API Model Refactoring

  • AnalyticsClient: New client for analytics operations (replaces UserApiClient)
  • Enhanced API Models:
    • AnalyticsResponse - Complex analytics data structure
    • MergedProduct - Product merger operations
    • TopProduct - Product with quantity tracking (extends base Product)
    • Product - New base product model with common fields
  • Inheritance-Based Models: ProductRequest and TopProduct inherit from Product base class

Database Layer Improvements

  • ProductEntity: Renamed from Product to avoid naming conflicts with API models
  • Repository Updates: All repositories updated to use ProductEntity
  • Test Data Updates: Faker and helper classes updated for new entity structure

Tracing Integration

  • Built-in Tracing: Playwright tracing integrated into PlaywrightSetup
  • Configurable Tracing: Control via appsettings.json or per-test parameters
  • Trace Viewer: New PowerShell script for easy trace viewing
  • Automatic Management: Traces saved automatically with test execution

Enhanced Developer Tools

  • Cross-Platform Codegen: Enhanced codegen-unix.ps1 with advanced options
  • Trace Viewer: PowerShell-based trace viewer with file management
  • Improved Scripts: Better error handling and cross-platform support

πŸ”„ CI/CD Integration

GitHub Actions Example

name: Test Automation

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    
    - name: Setup .NET
      uses: actions/setup-dotnet@v4
      with:
        dotnet-version: '9.0'
    
    - name: Install PowerShell
      run: |
        sudo apt-get update
        sudo apt-get install -y powershell
    
    - name: Install Playwright
      run: pwsh bin/Debug/net9.0/playwright.ps1 install --with-deps
    
    - name: Run Tests with Allure
      run: |
        pwsh ./run-allure-tests-unix.ps1
        pwsh ./reports/scripts/archive-reports-unix.ps1 -BuildNumber "${{ github.run_number }}" -Branch "${{ github.ref_name }}"
    
    - name: Upload Allure Results
      uses: actions/upload-artifact@v4
      if: always()
      with:
        name: allure-results-${{ github.run_number }}
        path: reports/allure-results/
    
    - name: Upload Traces
      uses: actions/upload-artifact@v4
      if: always()
      with:
        name: playwright-traces-${{ github.run_number }}
        path: bin/Debug/net9.0/Traces/

πŸ§ͺ Test Data Generation

Enhanced Fake Data Support

// Complete fake data for ProductEntity
var product = TestDataFaker.CreateFakeProduct();

// Mix of fake and specific data for API models
var productRequest = new ProductRequestBuilder()
    .WithFakeId()           // Random ID
    .WithFakeName()         // Random product name  
    .WithCategory("Laptops") // Specific category
    .WithFakePrice(50, 200) // Random price in range
    .Build();

// Direct faker usage
var email = TestDataFaker.FakeEmail();
var category = TestDataFaker.FakeCategory();
var price = TestDataFaker.FakePrice(10, 500);

// Database entities with fake data
var user = DatabaseTestHelper.CreateFakeUser();
var product = DatabaseTestHelper.CreateFakeProduct();

πŸ”§ Troubleshooting

Common Issues

Trace Files Not Generated

# Enable tracing in config
"Playwright": { "EnableTracing": true }

# Or per test
await LaunchBrowserAsync(BrowserList.Chrome, enableTracing: true);

# Check trace directory
pwsh ./trace-viewer.ps1 -List

Cross-Platform Script Issues

# Ensure PowerShell is installed
pwsh --version

# Use Unix scripts on Mac/Linux
pwsh ./run-allure-tests-unix.ps1
pwsh ./codegen-unix.ps1

API Model Conflicts

// Use fully qualified names if needed
using ApiProduct = atf.API.Models.Product;
using DataProduct = atf.Data.Models.ProductEntity;

Port Already in Use

# Scripts automatically find available ports
pwsh ./reports/scripts/open-report-unix.ps1 -Port 3000

🀝 Contributing

Code Style

  • Follow C# naming conventions
  • Use async/await for all I/O operations
  • Implement proper error handling with meaningful messages
  • Add XML documentation for public APIs
  • Maintain cross-platform compatibility for scripts

Testing Guidelines

  • One assertion per test when possible
  • Use descriptive test names that explain the scenario
  • Follow Arrange-Act-Assert pattern
  • Clean up resources in test teardown
  • Use appropriate Page Object approach (selector-based vs ILocator)

Pull Request Process

  1. Create feature branch from main
  2. Write tests for new functionality
  3. Ensure all tests pass locally with tracing enabled
  4. Update documentation if needed
  5. Submit PR with descriptive title and details

πŸ“„ License

This project is licensed under the MIT License.

πŸ†˜ Support

  • Issues: Report bugs and feature requests in GitHub Issues
  • Documentation: Additional docs in /Documentation folder
  • Examples: Sample tests in /Tests directory
  • Tracing: Use pwsh ./trace-viewer.ps1 (Windows) or pwsh ./trace-viewer-unix.ps1 (Unix/Mac) for visual debugging

Happy Testing! 🎯

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  
0