@liveauctioneers/api-test-lib
v0.0.9
Published
API Test Lib
Maintainers
Keywords
Readme
api-test-lib
Overview
This framework is designed to automate API testing for multiple services, including GAP, SLB, SBS, and TimedBidding. It utilizes Playwright for creating requests and MySQL2 for querying the ViewCache Database.
Features
- Multi-Service Support: Tests can be written for GAP, SLB, SBS, and TimedBidding services.
- Playwright Integration: Leverages Playwright for robust and reliable API request handling.
- MySQL2 Database Queries: Utilizes MySQL2 to query the ViewCache Database for data validation.
- Modular Structure: Organized into separate folders for configurations, fixtures, resources, services, tests, and utilities.
- Fixture-Based Service Initialization: Services are initialized using Playwright fixtures, simplifying test setup and ensuring consistent environments.
File Structure
- .env
- .env.example
- api.config.ts
- fixtures/
- package.json
- package-lock.json
- README.md
- resources/
- services/
- tests/
- utils/Setup Instructions
Clone the Repository:
git clone [email protected]:globalauctionplatform/api-test-lib.gitInstall Dependencies: Navigate into the cloned directory and install required packages:
npm installConfigure Environment Variables:
- Copy the
.env.examplefile to create a.envfile:cp .env.example .env - Update the
.envfile with your actual environment variables (e.g., database credentials, service endpoints).
- Copy the
Run Tests: Execute tests using the following command:
npm run test
Framework Architecture
File Structure
This structure organizes the framework into logical components:
- The root directory handles configuration and project metadata.
fixtures/,resources/, andutils/: Provide reusable components like test data, payloads, utilities, and models.services/: Encapsulates service-specific logic and endpoint definitions, as well as SQL query utility..tests/: Contains test cases organized by feature or service.
fixtures/
fixtures.ts
resources/
addressPayload.json
services/
gap/
AuctionApprovalEndpoint.ts
GapService.ts
QueryHelper.ts
slb/
AuctionEndpoint.ts
SlbService.ts
timed_bidding/
TimedBiddingService.ts
tests/
api/
api.spec.ts
utils/
DateUtils.ts
DBConnector.ts
models/
AuctionApprovalData.ts
.env
.env.example
api.config.ts
package.json
package-lock.json
README.mdRoot Directory
.env: Contains environment-specific variables, such as API keys, base URLs, and database credentials. This file should not be committed to version control..env.example: A template for.envthat lists all required environment variables without sensitive values.api.config.ts: Configuration file for the API testing framework. It may include setup details like base URLs, authentication tokens, and global configurations.package.json: Defines dependencies, scripts, and metadata for the project.package-lock.json: Locks the dependency tree to ensure consistent installations across environments.README.md: Documentation for the framework, including setup instructions, usage examples, and file structure.
fixtures/
fixtures.ts: Contains reusable test data or setup logic like service classes that can be injected into the test scenarios.
resources/
Contains JSON files with payloads used in API requests, for instance:
auctionPayload.json: Sample payload for auction-related operations.
services/
Contains service classes and endpoint definitions:
gap/AuctionApprovalEndpoint.ts: Defines methods for interacting with the auction approval endpoint (e.g., approving auctions).BidderRegistrationEndpoint.ts: Contains methods for bidder registration operations.GapService.ts: Initializes the GAP service and provides access to its endpoints.
QueryHelper.ts: A utility file that likely contains helper functions for querying data or performing common tasks across services.slb/AuctionEndpoint.ts: Contains methods for auction-related operations in SLB (e.g., creating auctions).
tests/
Contains test cases organized by feature or service:
api/api.spec.ts: Covers end-to-end scenarios for SBSv2
utils/
Utility functions and helpers used across the framework:
DateUtils.ts: Provides utility functions for handling dates and times (e.g., formatting, calculating durations).DBConnector.ts: Handles database connections and queries using MySQL2.models/:- Contains TypeScript models representing data structures used in requests or responses:
AuctionApprovalData.ts: Model for auction approval data.
- Contains TypeScript models representing data structures used in requests or responses:
Service Classes (FooService)
Services encapsulate configuration and expose endpoints. Example structure:
class FooService {
private baseUrl: string;
private headers: Record;
private apiContext: APIRequestContext;
public auctionApprovalEndpoint: AuctionApprovalEndpoint;
public bidderRegistrationEndpoint: BidderRegistrationEndpoint;
constructor(baseUrl: string, apiKey: string) {
this.baseUrl = baseUrl;
this.headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
};
this.apiContext = await request.newContext({
baseURL: this.baseUrl,
extraHTTPHeaders: this.headers
});
this.auctionApprovalEndpoint = new AuctionApprovalEndpoint(this.apiContext);
this.bidderRegistrationEndpoint = new BidderRegistrationEndpoint(this.apiContext);
}
}Endpoint Classes
Endpoint classes contain specific API operations:
class AuctionApprovalEndpoint {
constructor(private apiContext: APIRequestContext) {}
async createCustomer(payload: CustomerPayload): Promise {
return this.apiContext.post('/v1/auctions/approvals', {
data: payload
});
}
}Writing Tests
Tests are located in the tests/ directory. Services like gapService and slbService are initialized using Playwright fixtures, allowing you to use them directly in tests without manual setup.
Example Test Usage
test.only('Create auction Standard QA Environment', async ({ slbService, gapService }) => {
// Use services here
const createAuctionResponse = await slbService.auctionEndpoint.createAuction(AuctionCreationData.fromAuctionDuration(3, 'hour'));
const atgAuctionId = await createAuctionResponse.auctionDetails.atgAuctionId;
expect(atgAuctionId).toBeTruthy();
});Key Benefits
- Separation of Concerns:
- Services handle configuration
- Endpoints focus on specific API operations
- Reusability: Endpoint methods can be reused across test scenarios
- Type Safety: Strong typing for both payloads and responses
- Centralized Configuration: Base URL and headers managed in one place
Creating New Services
- Add a new service folder in
services/, likefoo/ - Create the service class following the
FooServicepattern - Create corresponding endpoints in
services/foo/ - Add the corresponding service entry in the
fixtures/fixtures.ts - Add the reference to the service Fixture in every scenario that needs it for test files in
tests// - Enjoy!
Database Connection and Query Utilities
utils/DBConnector.ts
This module is responsible for configuring and managing the database connection. It provides a method to execute SQL queries:
query(sql: string, params?: any[]): Executes a SQL query with optional parameters. This method is used throughout the framework to interact with the database.
utils/QueryHelper.ts
This utility class provides methods to query the database with retry logic for handling transient errors:
retryOperation(operation: () => Promise): A private method that retries a given asynchronous operation up toMAX_RETRIEStimes with a delay ofRETRY_DELAY_MSbetween attempts.getAuctionRecord(atgAuctionId: any): An example method that uses the retry logic to fetch an auction record from the database. This method is static and can be used across the framework.
Usage Example
import { QueryHelper } from './utils/QueryHelper';
// Fetch an auction record with retry logic
const auctionRecord = await QueryHelper.getAuctionRecord('foo');Contributing
Contributions are welcome! Please submit pull requests with detailed descriptions of changes.
Notes for Further Development
- Add API Documentation: Include detailed documentation for each service's API endpoints.
- Test Examples: Provide example test files for each service.
- CI/CD Integration: Integrate with CI/CD pipelines for automated testing on each commit.
