15 Commits

Author SHA1 Message Date
david 56a56e590e fix: add explicit --context and --file to all docker build commands 2026-05-14 18:17:53 -07:00
david 9a6188b2ae fix: use explicit --context and --file for docker build in CI 2026-05-14 18:16:54 -07:00
david fea0585a75 test: improve mock error handling and add test cleanup 2026-05-14 17:56:35 -07:00
david 820b1d8d84 fix: remove unused prisma import causing DATABASE_URL error in CI
Pull Request / unit-tests (pull_request) Failing after 1m14s
Pull Request / build-and-deploy-ci (pull_request) Has been skipped
Pull Request / analyze-bump-type (pull_request) Has been skipped
2026-05-07 03:25:46 -07:00
david 48b524ef84 remove push on ci build
Pull Request / unit-tests (pull_request) Failing after 1m4s
Pull Request / build-and-deploy-ci (pull_request) Has been skipped
Pull Request / analyze-bump-type (pull_request) Has been skipped
2026-05-07 03:16:14 -07:00
david e602e83642 sanitize docker tags
Pull Request / unit-tests (pull_request) Failing after 1m0s
Pull Request / build-and-deploy-ci (pull_request) Has been skipped
Pull Request / analyze-bump-type (pull_request) Has been skipped
2026-05-07 03:10:48 -07:00
david ac8562ea51 feat: implement full CI/CD pipeline with staged deployments
Pull Request / unit-tests (pull_request) Failing after 5m34s
Pull Request / build-and-deploy-ci (pull_request) Has been skipped
Pull Request / analyze-bump-type (pull_request) Has been skipped
- PR workflow: build, deploy to CI site, wait for health, run acceptance tests
- Release workflow: deploy to dev using mounted compose path with health check
- Add deploy-prod workflow (workflow_dispatch) for human-gated prod deployment
- Add just recipes: deploy-prod, status (view current image tags across envs)
- Runners now have /apps mount for access to all environment compose files
2026-05-07 02:30:30 -07:00
david b1c4e9a0ce ci: reduce retries to 1 and increase workers to 2
Pull Request / unit-tests (pull_request) Successful in 1m28s
Pull Request / analyze-bump-type (pull_request) Successful in 16s
Pull Request / acceptance-tests (pull_request) Failing after 10m4s
- Retries reduced from 2 to 1 (retries are helping with flaky remote tests but 2 is overkill)
- Workers increased from 1 to 2 in CI for parallel project execution
2026-05-03 18:04:01 -07:00
david 413ebaeaee fix: correct CI test configuration and Navigation test provider
Pull Request / unit-tests (pull_request) Successful in 1m25s
Pull Request / analyze-bump-type (pull_request) Successful in 12s
Pull Request / acceptance-tests (pull_request) Has been cancelled
- Wrap Navigation tests in RoleSwitcherProvider to fix 6 test failures
- Use remote CI server URL (euchre-ci.notsosm.art) for acceptance tests in CI
- Fix DATABASE_URL reference from vars to secrets in PR workflow
2026-05-03 17:35:39 -07:00
david f27efebd82 fix: add PrismaPg adapter for PostgreSQL and fix GRANT statements
Pull Request / unit-tests (pull_request) Failing after 1m28s
Pull Request / acceptance-tests (pull_request) Failing after 1m28s
Pull Request / analyze-bump-type (pull_request) Has been skipped
2026-05-03 17:08:16 -07:00
david 30ea4e4e86 ci: add acceptance tests job with CI database and sync-dev recipe 2026-05-03 16:31:45 -07:00
david 75cb6ed29d feat: add global teardown config and disable webServer in CI 2026-05-03 16:31:39 -07:00
david fa13ed86c9 fix: correct isProductionDatabase() to allow CI database and add schema reset 2026-05-03 16:31:36 -07:00
david 66e574d5ec docs: update .env.example with SDLC environment documentation 2026-05-03 16:27:50 -07:00
david a9138cfbe4 feat: add home page and rankings E2E tests with workflow improvements 2026-05-03 15:30:34 -07:00
45 changed files with 565 additions and 11151 deletions
+11 -7
View File
@@ -1,16 +1,19 @@
# EuchreCamp Environment Configuration # EuchreCamp Environment Configuration
# ============================================ # ============================================
# Copy this file to .env or use # Copy this file to .env (for local dev) or use
# .env.development / .env.production for specific environments # .env.development / .env.ci for specific environments
# ============================================ # ============================================
# Database Configuration # Database Configuration
# ============================================ # ============================================
# IMPORTANT: Use the appropriate DATABASE_URL for your environment: # IMPORTANT: Use the appropriate DATABASE_URL for your environment:
# #
# - Development: euchre_camp_dev (in .env.development) # - Development (ephemeral, synced from prod): euchre_camp_dev
# - CI/Testing: euchre_camp_ci (set via CI_DATABASE_URL secret) # - CI/Testing (reset before each run): euchre_camp_ci
# - Production: euchre_camp (in .env.production, DO NOT USE FOR TESTS) # - Production (DO NOT USE FOR TESTS): euchre_camp
#
# The .credentials file in the project root contains
# the actual connection strings - DO NOT commit .credentials
DATABASE_PROVIDER=postgresql DATABASE_PROVIDER=postgresql
@@ -39,6 +42,7 @@ TRUSTED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
# NODE_ENV=development # NODE_ENV=development
# BETTER_AUTH_URL=http://localhost:3000 # BETTER_AUTH_URL=http://localhost:3000
# #
# For CI (set via secrets): # For CI (.env.ci):
# DATABASE_URL set as CI_DATABASE_URL secret (euchre_camp_ci) # DATABASE_URL from .credentials (euchre_camp_ci)
# NODE_ENV=test # NODE_ENV=test
# BETTER_AUTH_URL=http://localhost:3000
+5 -5
View File
@@ -132,11 +132,11 @@ When a PR is merged to `main`:
## Database Configuration for CI ## Database Configuration for CI
### PostgreSQL for CI Acceptance Tests ### SQLite for CI Acceptance Tests
- **Why PostgreSQL**: Matches production database, catches PG-specific issues - **Why SQLite**: No database server required, perfect for CI environments
- **Usage**: PR workflow runs acceptance tests with PostgreSQL database - **Usage**: PR workflow runs acceptance tests with SQLite database
- **Configuration**: `CI_DATABASE_URL` secret, set as `DATABASE_URL` env var - **Configuration**: `DATABASE_PROVIDER=sqlite`, `DATABASE_URL=file:./prisma/ci.db`
- **Benefits**: Production-like environment, consistent with dev and prod - **Benefits**: Fast, isolated, no external dependencies
### PostgreSQL for Production ### PostgreSQL for Production
- **Usage**: Release workflow runs tests in Docker with PostgreSQL - **Usage**: Release workflow runs tests in Docker with PostgreSQL
+4 -4
View File
@@ -8,7 +8,6 @@ on:
- "Dockerfile.ci-base" - "Dockerfile.ci-base"
- "package.json" - "package.json"
- "bun.lock" - "bun.lock"
- "package-lock.json"
- ".gitea/workflows/build-ci-images.yml" - ".gitea/workflows/build-ci-images.yml"
schedule: schedule:
# Weekly rebuild to get latest Playwright/Bun versions # Weekly rebuild to get latest Playwright/Bun versions
@@ -53,13 +52,14 @@ jobs:
- name: Build and push CI base image - name: Build and push CI base image
run: | run: |
WORKSPACE_DIR="$GITHUB_WORKSPACE"
# Build with multiple tags
docker build \ docker build \
--file Dockerfile.ci-base \ --context "$WORKSPACE_DIR" \
--file "$WORKSPACE_DIR/Dockerfile.ci-base" \
--tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:latest \ --tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:latest \
--tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:playwright-${{ steps.meta.outputs.playwright_version }} \ --tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:playwright-${{ steps.meta.outputs.playwright_version }} \
--tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:${{ github.sha }} \ --tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}/ci-base:${{ github.sha }} \
--push \
.
- name: Clean up - name: Clean up
if: always() if: always()
+2 -2
View File
@@ -40,12 +40,12 @@ jobs:
# Wait for production site to be healthy # Wait for production site to be healthy
echo "Waiting for production site to be healthy..." echo "Waiting for production site to be healthy..."
for i in {1..6}; do for i in {1..30}; do
if curl -sf https://euchre.notsosm.art/api/health > /dev/null 2>&1; then if curl -sf https://euchre.notsosm.art/api/health > /dev/null 2>&1; then
echo "✅ Production successfully deployed with version ${VERSION}" echo "✅ Production successfully deployed with version ${VERSION}"
exit 0 exit 0
fi fi
sleep 15 sleep 0.5
done done
echo "❌ Production deployment failed" echo "❌ Production deployment failed"
docker compose logs app docker compose logs app
+19 -22
View File
@@ -15,21 +15,21 @@ jobs:
container: container:
image: docker.notsosm.art/euchre-camp/ci-base:latest image: docker.notsosm.art/euchre-camp/ci-base:latest
options: --user root options: --user root
env:
DATABASE_URL: postgresql://user:pass@localhost:5432/dummy
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Install dependencies - name: Install dependencies
run: npm ci --legacy-peer-deps run: bun install
- name: Generate Prisma client - name: Generate Prisma client
run: npx prisma generate run: bun x prisma generate
env:
DATABASE_URL: postgresql://user:pass@localhost:5432/dummy
- name: Run unit tests - name: Run unit tests
run: npm test run: bun test src/__tests__/unit/ src/__tests__/*.test.tsx src/__tests__/auth-simple.test.ts
build-and-deploy-ci: build-and-deploy-ci:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -37,20 +37,16 @@ jobs:
container: container:
image: docker.notsosm.art/euchre-camp/ci-base:latest image: docker.notsosm.art/euchre-camp/ci-base:latest
options: --user root options: --user root
volumes:
- /var/lib/casaos/apps:/apps
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
# Required for acceptance tests - they import prisma via @/ path alias
# and @cucumber/cucumber for cucumber-e2e tests
- name: Install dependencies - name: Install dependencies
run: npm ci --legacy-peer-deps run: bun install
- name: Generate Prisma client - name: Generate Prisma client
run: npx prisma generate run: bun x prisma generate
env: env:
DATABASE_URL: postgresql://user:pass@localhost:5432/dummy DATABASE_URL: postgresql://user:pass@localhost:5432/dummy
@@ -62,12 +58,15 @@ jobs:
- name: Build Docker image for PR - name: Build Docker image for PR
run: | run: |
WORKSPACE_DIR="$GITHUB_WORKSPACE"
IMAGE_TAG="pr-${{ steps.info.outputs.pr_number }}-${{ steps.info.outputs.short_sha }}" IMAGE_TAG="pr-${{ steps.info.outputs.pr_number }}-${{ steps.info.outputs.short_sha }}"
docker build \ docker build \
--context "$WORKSPACE_DIR" \
--file "$WORKSPACE_DIR/Dockerfile" \
--target runner \ --target runner \
--build-arg GIT_COMMIT=$GITHUB_SHA \ --build-arg GIT_COMMIT=$GITHUB_SHA \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${IMAGE_TAG} \ -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${IMAGE_TAG} \
. "$WORKSPACE_DIR"
- name: Update CI site compose and restart - name: Update CI site compose and restart
run: | run: |
@@ -77,34 +76,33 @@ jobs:
# Update the image tag in the compose file # Update the image tag in the compose file
sed -i "s|image: docker.notsosm.art/euchre-camp:[a-zA-Z0-9.-]*|image: docker.notsosm.art/euchre-camp:${IMAGE_TAG}|" ${COMPOSE_FILE} sed -i "s|image: docker.notsosm.art/euchre-camp:[a-zA-Z0-9.-]*|image: docker.notsosm.art/euchre-camp:${IMAGE_TAG}|" ${COMPOSE_FILE}
# Image was built locally in the previous step; compose uses it without pulling # Pull the new image and restart the CI stack
cd /apps/euchre_camp_ci cd /apps/euchre_camp_ci
docker compose pull app
docker compose up -d app docker compose up -d app
- name: Wait for CI site to be ready - name: Wait for CI site to be healthy
run: | run: |
echo "Waiting for Next.js to start..." for i in {1..30}; do
sleep 20
for i in {1..6}; do
if curl -sf https://euchre-ci.notsosm.art/api/health > /dev/null 2>&1; then if curl -sf https://euchre-ci.notsosm.art/api/health > /dev/null 2>&1; then
echo "CI site is healthy" echo "CI site is healthy"
exit 0 exit 0
fi fi
sleep 15 sleep 0.5
done done
echo "CI site failed to become healthy after 90 seconds" echo "CI site failed to become healthy after 15 seconds"
docker compose -f /apps/euchre_camp_ci/docker-compose.yml logs app docker compose -f /apps/euchre_camp_ci/docker-compose.yml logs app
exit 1 exit 1
- name: Run acceptance tests - name: Run acceptance tests
run: DATABASE_URL="${{ secrets.CI_DATABASE_URL }}" npx playwright test e2e/ run: DATABASE_URL="${{ secrets.CI_DATABASE_URL }}" bun test:acceptance
env: env:
CI: true CI: true
- name: Cleanup PR images - name: Cleanup PR images
if: always() if: always()
run: | run: |
docker rmi --force ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:pr-${{ steps.info.outputs.pr_number }}-${{ steps.info.outputs.short_sha }} || true docker rmi ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:pr-${{ steps.info.outputs.pr_number }}-${{ steps.info.outputs.short_sha }} || true
analyze-bump-type: analyze-bump-type:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -148,7 +146,6 @@ jobs:
echo "reason=$REASON" >> $GITHUB_OUTPUT echo "reason=$REASON" >> $GITHUB_OUTPUT
- name: Comment bump type on PR - name: Comment bump type on PR
if: github.event_name == 'pull_request'
uses: actions/github-script@v7 uses: actions/github-script@v7
with: with:
script: | script: |
+13 -8
View File
@@ -73,10 +73,10 @@ jobs:
echo "Bumping version: $BUMP" echo "Bumping version: $BUMP"
# Run the bump script # Run the bump script
node scripts/bump-version.js "$BUMP" --yes bun run scripts/bump-version.js "$BUMP" --yes
# Get new version # Get new version
NEW_VERSION=$(node -e "console.log(require('./package.json').version)") NEW_VERSION=$(bun -e "console.log(require('./package.json').version)")
echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
echo "New version: $NEW_VERSION" echo "New version: $NEW_VERSION"
@@ -110,30 +110,35 @@ jobs:
- name: Build test-capable image - name: Build test-capable image
if: steps.commit.outputs.committed == 'true' if: steps.commit.outputs.committed == 'true'
run: | run: |
WORKSPACE_DIR="$GITHUB_WORKSPACE"
docker build \ docker build \
--context "$WORKSPACE_DIR" \
--file "$WORKSPACE_DIR/Dockerfile" \
--target test-runner \ --target test-runner \
--build-arg GIT_COMMIT=${{ github.sha }} \ --build-arg GIT_COMMIT=${{ github.sha }} \
-t ${{ env.IMAGE_NAME }}-test:${{ steps.version.outputs.new_version }} \ -t ${{ env.IMAGE_NAME }}-test:${{ steps.version.outputs.new_version }} \
. "$WORKSPACE_DIR"
- name: Run tests inside test-capable container - name: Run tests inside test-capable container
if: steps.commit.outputs.committed == 'true' if: steps.commit.outputs.committed == 'true'
run: | run: |
docker run --rm \ docker run --rm \
-e DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" \ -e DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" \
-e NODE_ENV=test \
${{ env.IMAGE_NAME }}-test:${{ steps.version.outputs.new_version }} \ ${{ env.IMAGE_NAME }}-test:${{ steps.version.outputs.new_version }} \
npm test bun test 'src/__tests__/unit/**' 'src/__tests__/*.test.tsx' 'src/__tests__/auth-simple.test.ts'
- name: Build production image - name: Build production image
if: steps.commit.outputs.committed == 'true' if: steps.commit.outputs.committed == 'true'
run: | run: |
WORKSPACE_DIR="$GITHUB_WORKSPACE"
docker build \ docker build \
--context "$WORKSPACE_DIR" \
--file "$WORKSPACE_DIR/Dockerfile" \
--target runner \ --target runner \
--build-arg GIT_COMMIT=${{ github.sha }} \ --build-arg GIT_COMMIT=${{ github.sha }} \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.new_version }} \ -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.new_version }} \
-t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest \ -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest \
. "$WORKSPACE_DIR"
- name: Push Docker images - name: Push Docker images
if: steps.commit.outputs.committed == 'true' if: steps.commit.outputs.committed == 'true'
@@ -177,12 +182,12 @@ jobs:
# Wait for container to be healthy # Wait for container to be healthy
echo "Waiting for dev site to be healthy..." echo "Waiting for dev site to be healthy..."
for i in {1..6}; do for i in {1..30}; do
if curl -sf https://euchre-dev.notsosm.art/api/health > /dev/null 2>&1; then if curl -sf https://euchre-dev.notsosm.art/api/health > /dev/null 2>&1; then
echo "✅ Dev environment successfully deployed with version ${{ steps.version.outputs.new_version }}" echo "✅ Dev environment successfully deployed with version ${{ steps.version.outputs.new_version }}"
exit 0 exit 0
fi fi
sleep 15 sleep 0.5
done done
echo "❌ Dev environment deployment failed" echo "❌ Dev environment deployment failed"
docker compose logs app docker compose logs app
+2 -1
View File
@@ -15,7 +15,8 @@
/playwright/.auth/ /playwright/.auth/
/test-results /test-results
/cookies.txt /cookies.txt
# .env.test was removed — tests use DATABASE_URL from shell or .env.development .env.test
prisma/ci.db
# next.js # next.js
/.next/ /.next/
+2 -2
View File
@@ -165,9 +165,9 @@ npm run db:setup-postgres
- **Acceptance tests**: `npm run test:acceptance` - **Acceptance tests**: `npm run test:acceptance`
- **Specific test**: `npm run test:acceptance -- --grep "test name"` - **Specific test**: `npm run test:acceptance -- --grep "test name"`
**CI-style acceptance tests (uses PostgreSQL, set DATABASE_URL in your shell):** **CI-style acceptance tests with SQLite:**
```bash ```bash
DATABASE_PROVIDER=postgresql DATABASE_URL="your_dev_db_url" npm run test:acceptance DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db npm run test:acceptance
``` ```
### CI Runner Image ### CI Runner Image
-7
View File
@@ -1,10 +1,3 @@
## [0.1.21] - 2026-05-20
### Patch Changes
- fix: mount /apps and docker socket in PR workflow build-and-deploy-ci job (#41)
- feat: SDLC database separation for CI/testing (#35)
## [0.1.20] - 2026-05-02 ## [0.1.20] - 2026-05-02
### Patch Changes ### Patch Changes
+11 -11
View File
@@ -4,7 +4,7 @@
FROM oven/bun:alpine AS builder FROM oven/bun:alpine AS builder
# Install dependencies (needed for native modules) # Install dependencies (needed for native modules)
RUN apk add --no-cache python3 make g++ nodejs npm RUN apk add --no-cache python3 make g++
# Set working directory # Set working directory
WORKDIR /app WORKDIR /app
@@ -13,14 +13,14 @@ WORKDIR /app
COPY package*.json ./ COPY package*.json ./
# Install dependencies (including dev dependencies for building) # Install dependencies (including dev dependencies for building)
RUN npm ci --legacy-peer-deps RUN bun install
# Copy source code # Copy source code
COPY . . COPY . .
# Generate Prisma client (with dummy PostgreSQL DATABASE_URL for build-time generation) # Generate Prisma client (with dummy PostgreSQL DATABASE_URL for build-time generation)
# Note: A dummy URL is used since the real database is not available during build # Note: A dummy URL is used since the real database is not available during build
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" npx prisma generate RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" bun x prisma generate
# Build the application (with dummy DATABASE_URL for static page generation and git commit) # Build the application (with dummy DATABASE_URL for static page generation and git commit)
ARG GIT_COMMIT=unknown ARG GIT_COMMIT=unknown
@@ -30,7 +30,7 @@ RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:
FROM oven/bun:alpine AS test-runner FROM oven/bun:alpine AS test-runner
# Install dependencies # Install dependencies
RUN apk add --no-cache python3 make g++ git nodejs npm RUN apk add --no-cache python3 make g++ git
# Set working directory # Set working directory
WORKDIR /app WORKDIR /app
@@ -39,19 +39,19 @@ WORKDIR /app
COPY package*.json ./ COPY package*.json ./
# Install ALL dependencies (including dev dependencies for testing) # Install ALL dependencies (including dev dependencies for testing)
RUN npm ci --legacy-peer-deps RUN bun install
# Copy source code # Copy source code
COPY . . COPY . .
# Generate Prisma client # Generate Prisma client
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" npx prisma generate RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" bun x prisma generate
# Stage 3: Production runner # Stage 3: Production runner
FROM oven/bun:alpine AS runner FROM oven/bun:alpine AS runner
# Install dumb-init and npm for production install # Install dumb-init for proper signal handling
RUN apk add --no-cache dumb-init nodejs npm RUN apk add --no-cache dumb-init
# Create non-root user # Create non-root user
RUN addgroup --system --gid 1001 euchre && \ RUN addgroup --system --gid 1001 euchre && \
@@ -64,15 +64,15 @@ WORKDIR /app
COPY --from=builder --chown=euchre:euchre /app/.next ./.next COPY --from=builder --chown=euchre:euchre /app/.next ./.next
COPY --from=builder --chown=euchre:euchre /app/public ./public COPY --from=builder --chown=euchre:euchre /app/public ./public
COPY --from=builder --chown=euchre:euchre /app/package.json ./package.json COPY --from=builder --chown=euchre:euchre /app/package.json ./package.json
COPY --from=builder --chown=euchre:euchre /app/package-lock.json ./package-lock.json COPY --from=builder --chown=euchre:euchre /app/bun.lock ./bun.lock
COPY --from=builder --chown=euchre:euchre /app/prisma ./prisma COPY --from=builder --chown=euchre:euchre /app/prisma ./prisma
# Install only production dependencies # Install only production dependencies
RUN npm ci --legacy-peer-deps --omit=dev RUN bun install --production
# Generate Prisma client # Generate Prisma client
# Note: We need to set DATABASE_URL even for generation because prisma.config.ts requires it # Note: We need to set DATABASE_URL even for generation because prisma.config.ts requires it
RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" npx prisma generate RUN DATABASE_PROVIDER=postgresql DATABASE_URL="postgresql://user:pass@localhost:5432/dummy" bun x prisma generate
# Switch to non-root user # Switch to non-root user
USER euchre USER euchre
+4 -4
View File
@@ -294,8 +294,8 @@ npm run test
# Run acceptance tests # Run acceptance tests
npm run test:acceptance npm run test:acceptance
# Run acceptance tests (CI-style, set DATABASE_URL in your shell) # Run acceptance tests with SQLite (CI-style)
DATABASE_PROVIDER=postgresql DATABASE_URL="your_dev_db_url" npm run test:acceptance DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db npm run test:acceptance
``` ```
### Database Commands ### Database Commands
@@ -400,8 +400,8 @@ The original attempt to use a pre-built CI runner image with pre-installed depen
# Run unit tests (same as CI) # Run unit tests (same as CI)
npm run test:run npm run test:run
# Run acceptance tests (set DATABASE_URL in your shell) # Run acceptance tests with SQLite
DATABASE_PROVIDER=postgresql DATABASE_URL="your_dev_db_url" npm run test:acceptance DATABASE_PROVIDER=sqlite DATABASE_URL=file:./prisma/ci.db npm run test:acceptance
``` ```
## Docker Deployment ## Docker Deployment
+4 -6
View File
@@ -10,8 +10,6 @@
import { test, expect } from '@playwright/test'; import { test, expect } from '@playwright/test';
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
// Generate unique test account credentials // Generate unique test account credentials
function getTestCredentials() { function getTestCredentials() {
const timestamp = Date.now(); const timestamp = Date.now();
@@ -54,14 +52,14 @@ test.describe.serial('Account Lifecycle API Acceptance Test', () => {
console.log('Test 1 - testEmail:', testEmail); console.log('Test 1 - testEmail:', testEmail);
// Register via API // Register via API
const response = await request.post('/api/auth/sign-up/email', { const response = await request.post('http://localhost:3000/api/auth/sign-up/email', {
data: { data: {
email: testEmail, email: testEmail,
password: testPassword, password: testPassword,
name: testName name: testName
}, },
headers: { headers: {
'Origin': BASE_URL 'Origin': 'http://localhost:3000'
} }
}); });
@@ -98,13 +96,13 @@ test.describe.serial('Account Lifecycle API Acceptance Test', () => {
} }
// Login via API // Login via API
const response = await request.post('/api/auth/sign-in/email', { const response = await request.post('http://localhost:3000/api/auth/sign-in/email', {
data: { data: {
email: testEmail, email: testEmail,
password: testPassword password: testPassword
}, },
headers: { headers: {
'Origin': BASE_URL 'Origin': 'http://localhost:3000'
} }
}); });
+1 -1
View File
@@ -74,7 +74,7 @@ test.describe.serial('Account Lifecycle Acceptance Test', () => {
await page.waitForURL(/\/players\/\d+\/profile/, { timeout: 10000 }); await page.waitForURL(/\/players\/\d+\/profile/, { timeout: 10000 });
// Wait a moment for the user to be saved to database // Wait a moment for the user to be saved to database
await page.waitForTimeout(200); await page.waitForTimeout(1000);
// Verify user was created in database // Verify user was created in database
const user = await prisma.user.findUnique({ const user = await prisma.user.findUnique({
+1 -1
View File
@@ -11,7 +11,7 @@
import { test, expect } from '@playwright/test' import { test, expect } from '@playwright/test'
import { prisma } from '@/lib/prisma' import { prisma } from '@/lib/prisma'
test.describe.skip('Admin Features: Match and Player Management @chromium-admin', () => { test.describe('Admin Features: Match and Player Management @chromium-admin', () => {
test.describe('Match Management', () => { test.describe('Match Management', () => {
test('should access matches admin page', async ({ page }) => { test('should access matches admin page', async ({ page }) => {
await page.goto('/admin/matches') await page.goto('/admin/matches')
-92
View File
@@ -1,92 +0,0 @@
import { test, expect } from '@playwright/test'
test.describe.skip('Admin Smoke Test', () => {
test.describe('Admin Panel Navigation', () => {
test('should navigate to admin dashboard', async ({ page }) => {
await page.goto('/admin')
await expect(page.locator('text=Admin')).toBeVisible()
})
test('should navigate to matches admin page', async ({ page }) => {
await page.goto('/admin/matches')
await expect(page.locator('text=Match Management')).toBeVisible()
})
test('should navigate to players admin page', async ({ page }) => {
await page.goto('/admin/players')
await expect(page.locator('text=Player Management')).toBeVisible()
})
test('should navigate to users admin page', async ({ page }) => {
await page.goto('/admin/users')
await expect(page.locator('text=User Management')).toBeVisible()
})
})
test.describe('Match Management', () => {
test('should display matches page', async ({ page }) => {
await page.goto('/admin/matches')
await expect(page.locator('text=Match Management')).toBeVisible()
const hasTable = await page.locator('table').count().then(c => c > 0)
const hasEmptyState = await page.locator('text=/no matches|No matches/').count().then(c => c > 0)
expect(hasTable || hasEmptyState).toBeTruthy()
})
test('should have delete button for matches when matches exist', async ({ page }) => {
await page.goto('/admin/matches')
const deleteButtons = page.locator('button:has-text("Delete")')
const count = await deleteButtons.count()
if (count > 0) {
await expect(page.locator('text=Actions')).toBeVisible()
}
})
})
test.describe('Player Management', () => {
test('should display players table', async ({ page }) => {
await page.goto('/admin/players')
await expect(page.locator('table')).toBeVisible()
await expect(page.locator('text=Player Name')).toBeVisible()
await expect(page.locator('text=Current Elo')).toBeVisible()
await expect(page.locator('text=Actions')).toBeVisible()
})
test('should have edit and delete buttons for players', async ({ page }) => {
await page.goto('/admin/players')
await expect(page.locator('text=Actions')).toBeVisible()
})
test('should allow editing player name', async ({ page }) => {
await page.goto('/admin/players')
const editButton = page.locator('button:has-text("Edit")').first()
if (await editButton.isVisible()) {
await editButton.click()
await expect(page.locator('text=Edit Player Name')).toBeVisible()
await page.click('text=Cancel')
await expect(page.locator('text=Edit Player Name')).not.toBeVisible()
}
})
})
test.describe('User Management', () => {
test('should display users page', async ({ page }) => {
await page.goto('/admin/users')
const hasTable = await page.locator('table').isVisible().catch(() => false)
const hasNoUsers = await page.locator('text=No users found').isVisible().catch(() => false)
expect(hasTable || hasNoUsers).toBeTruthy()
await expect(page.locator('text=User Management')).toBeVisible()
})
test('should have create user link', async ({ page }) => {
await page.goto('/admin/users')
const createLink = page.locator('a.bg-green-600:has-text("Create User")')
await expect(createLink).toBeVisible()
})
})
})
+12 -24
View File
@@ -10,10 +10,9 @@ import fs from 'fs';
import path from 'path'; import path from 'path';
test.describe.skip('CSV Upload Player Deduplication', () => { test.describe('CSV Upload Player Deduplication', () => {
let testTournamentId: number; let testTournamentId: number;
const testPlayerIds: number[] = []; const testPlayerIds: number[] = [];
const ts = Date.now();
test.beforeAll(async () => { test.beforeAll(async () => {
// Create a test tournament // Create a test tournament
@@ -48,14 +47,12 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
}); });
} }
// Delete test players (those with "Dedupe" or "Aggregate Test" in the name) // Delete test players (those with "Dedupe" in the name)
await prisma.player.deleteMany({ await prisma.player.deleteMany({
where: { where: {
OR: [ name: {
{ name: { contains: 'Dedupe' } }, contains: 'Dedupe',
{ name: { contains: 'Aggregate Test' } }, },
{ name: { contains: 'Whitespace' } },
],
}, },
}); });
@@ -81,13 +78,10 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
formData.append('csvFile', file); formData.append('csvFile', file);
formData.append('eventId', testTournamentId.toString()); formData.append('eventId', testTournamentId.toString());
const response = await request.post('/api/matches/upload', { const response = await request.post('http://localhost:3000/api/matches/upload', {
multipart: formData, multipart: formData,
}); });
if (!response.ok()) {
console.log('CSV upload failed:', response.status(), await response.text());
}
expect(response.ok()).toBeTruthy(); expect(response.ok()).toBeTruthy();
// Check that only 4 unique players were created (not 8) // Check that only 4 unique players were created (not 8)
@@ -138,13 +132,10 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
formData.append('csvFile', file); formData.append('csvFile', file);
formData.append('eventId', testTournamentId.toString()); formData.append('eventId', testTournamentId.toString());
const response = await request.post('/api/matches/upload', { const response = await request.post('http://localhost:3000/api/matches/upload', {
multipart: formData, multipart: formData,
}); });
if (!response.ok()) {
console.log('CSV upload failed:', response.status(), await response.text());
}
expect(response.ok()).toBeTruthy(); expect(response.ok()).toBeTruthy();
// Check that players were created without extra whitespace // Check that players were created without extra whitespace
@@ -172,8 +163,8 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
// First, create some players manually to simulate previous uploads // First, create some players manually to simulate previous uploads
const player1 = await prisma.player.create({ const player1 = await prisma.player.create({
data: { data: {
name: `Aggregate Test ${ts}`, name: 'Aggregate Test',
normalizedName: `aggregate test ${ts}`, normalizedName: 'aggregate test',
currentElo: 1050, currentElo: 1050,
gamesPlayed: 5, gamesPlayed: 5,
wins: 3, wins: 3,
@@ -184,7 +175,7 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
// Upload a CSV with the same player name // Upload a CSV with the same player name
const csvContent = `Event #,Round,Table,Seat 1,Seat 3,Odds Points,Seat 2,Seat 4,Evens Points const csvContent = `Event #,Round,Table,Seat 1,Seat 3,Odds Points,Seat 2,Seat 4,Evens Points
1,1,1,Aggregate Test ${ts},Test Player 1,5,Test Player 2,Test Player 3,3`; 1,1,1,Aggregate Test,Test Player 1,5,Test Player 2,Test Player 3,3`;
const csvPath = path.join(__dirname, 'temp-aggregate-test.csv'); const csvPath = path.join(__dirname, 'temp-aggregate-test.csv');
fs.writeFileSync(csvPath, csvContent); fs.writeFileSync(csvPath, csvContent);
@@ -198,19 +189,16 @@ test.describe.skip('CSV Upload Player Deduplication', () => {
formData.append('csvFile', file); formData.append('csvFile', file);
formData.append('eventId', testTournamentId.toString()); formData.append('eventId', testTournamentId.toString());
const response = await request.post('/api/matches/upload', { const response = await request.post('http://localhost:3000/api/matches/upload', {
multipart: formData, multipart: formData,
}); });
if (!response.ok()) {
console.log('CSV upload failed:', response.status(), await response.text());
}
expect(response.ok()).toBeTruthy(); expect(response.ok()).toBeTruthy();
// Check that the existing player was updated (not duplicated) // Check that the existing player was updated (not duplicated)
const aggregatePlayers = await prisma.player.findMany({ const aggregatePlayers = await prisma.player.findMany({
where: { where: {
name: `Aggregate Test ${ts}`, name: 'Aggregate Test',
}, },
}); });
+39 -26
View File
@@ -1,32 +1,45 @@
/**
* Bridge file to run Cucumber tests through Playwright's test runner
*
* This allows Cucumber tests to benefit from Playwright's:
* - Dev server management
* - Browser lifecycle management
* - Test reporting
* - CI/CD integration
*/
import { test } from '@playwright/test'; import { test } from '@playwright/test';
import { execSync } from 'child_process'; import { execSync } from 'child_process';
test.describe.skip('Cucumber E2E Tests', () => { // This test file doesn't contain actual tests
// It just runs Cucumber CLI which executes the feature files
test.describe('Cucumber E2E Tests', () => {
test('Run all Cucumber feature files', async () => { test('Run all Cucumber feature files', async () => {
const baseURL = process.env.CI // This test is a placeholder that triggers Cucumber execution
? 'https://euchre-ci.notsosm.art' // In practice, Cucumber should be run directly via CLI
: 'http://localhost:3000'; console.log('Cucumber tests should be run via: bun cucumber-js');
let result;
try {
result = execSync(
'npx cucumber-js --config e2e/cucumber/cucumber.config.ts',
{
encoding: 'utf-8',
stdio: 'pipe',
env: {
...process.env,
BASE_URL: baseURL,
},
cwd: process.cwd(),
}
);
} catch (error: any) {
console.log('Cucumber stderr:', error.stderr?.toString() || 'none');
console.log('Cucumber stdout:', error.stdout?.toString() || 'none');
throw error;
}
console.log(result);
}); });
}); });
/**
* Alternative approach: Programmatic execution
*
* If you want to run Cucumber programmatically from within Playwright:
*/
/*
import { execSync } from 'child_process';
export default async function runCucumberTests() {
try {
const output = execSync(
'bun cucumber-js --config e2e/cucumber/cucumber.config.ts',
{ encoding: 'utf-8', stdio: 'inherit' }
);
console.log(output);
return true;
} catch (error) {
console.error('Cucumber tests failed:', error);
return false;
}
}
*/
+2 -1
View File
@@ -17,7 +17,8 @@ module.exports = {
// Format options // Format options
format: [ format: [
process.env.CI ? 'progress' : ['pretty', 'html:cucumber-report.html'] 'progress-bar',
'pretty:cucumber-pretty'
], ],
// Output directory for reports // Output directory for reports
-5
View File
@@ -3,11 +3,6 @@ Feature: Home Page
I want to see the home page I want to see the home page
So that I can learn about the club and view player rankings So that I can learn about the club and view player rankings
Background:
Given there are top players in the system
And there is a club president
And there is a recent tournament
@happy-path @public @home @happy-path @public @home
Scenario: Home page displays Top 10 Players Scenario: Home page displays Top 10 Players
Given I am on the home page Given I am on the home page
+24 -42
View File
@@ -127,7 +127,7 @@ Given('I am logged in as a tournament admin', async function () {
// Wait for any redirect away from register page // Wait for any redirect away from register page
await world.page.waitForURL((url) => !url.toString().includes('/auth/register'), { timeout: 15000 }); await world.page.waitForURL((url) => !url.toString().includes('/auth/register'), { timeout: 15000 });
await world.page.waitForLoadState('domcontentloaded'); await world.page.waitForLoadState('networkidle');
await world.page.waitForTimeout(1000); await world.page.waitForTimeout(1000);
const currentUrl = world.page.url(); const currentUrl = world.page.url();
@@ -166,7 +166,7 @@ Given('I am logged in as a tournament admin', async function () {
// Navigate to trigger a fresh role fetch // Navigate to trigger a fresh role fetch
await world.page.goto(`${world.baseURL}/rankings`); await world.page.goto(`${world.baseURL}/rankings`);
await world.page.waitForLoadState('domcontentloaded'); await world.page.waitForLoadState('networkidle');
await world.page.waitForTimeout(500); await world.page.waitForTimeout(500);
} else { } else {
console.log(`🌍 WARNING: User not found in DB by email. Trying to find latest user...`); console.log(`🌍 WARNING: User not found in DB by email. Trying to find latest user...`);
@@ -235,7 +235,7 @@ Given('I am logged in as a site admin', async function () {
// Navigate to home page to trigger Navigation re-mount with new role // Navigate to home page to trigger Navigation re-mount with new role
await world.page.goto(`${world.baseURL}/`); await world.page.goto(`${world.baseURL}/`);
await world.page.waitForLoadState('domcontentloaded'); await world.page.waitForLoadState('networkidle');
await world.page.waitForTimeout(1000); await world.page.waitForTimeout(1000);
} }
} }
@@ -245,53 +245,35 @@ Given('I am logged in as a site admin', async function () {
/** /**
* Precondition: I am logged in as a club admin * Precondition: I am logged in as a club admin
* Creates a new user via UI and assigns club_admin role via Prisma * Uses a pre-existing admin user from the database
*/ */
Given('I am logged in as a club admin', async function () { Given('I am logged in as a club admin', async function () {
console.log('🌍 Creating and logging in as a club admin...'); console.log('🌍 Logging in as existing club admin...');
const credentials = generateTestCredentials(); // Use the admin user created by seed.js
world.user = credentials; const adminEmail = 'david@dhg.lol';
const adminPassword = 'adminadmin';
await world.page.goto(`${world.baseURL}/auth/register`); world.user = {
email: adminEmail,
password: adminPassword,
name: 'David Admin',
};
await world.page.goto(`${world.baseURL}/auth/login`);
await world.page.waitForLoadState('domcontentloaded'); await world.page.waitForLoadState('domcontentloaded');
await world.page.fill('input[name="name"]', credentials.name); await world.page.fill('input[name="email"]', adminEmail);
await world.page.fill('input[name="email"]', credentials.email); await world.page.fill('input[name="password"]', adminPassword);
await world.page.fill('input[name="password"]', credentials.password);
await world.page.click('button[type="submit"]'); await world.page.click('button[type="submit"]');
await world.page.waitForURL(/\/players\/\d+\/profile/, { timeout: 15000 });
const currentUrl = world.page.url(); // Wait for redirect after login
const match = currentUrl.match(/\/players\/(\d+)\/profile/); try {
if (match) { await world.page.waitForURL((url) => !url.toString().includes('/auth/login'), { timeout: 10000 });
const playerId = match[1]; console.log(`🌍 Club admin logged in: ${adminEmail}`);
world.playerId = playerId; } catch (e) {
console.log('🌍 Login redirect timed out, current URL:', world.page.url());
const prisma = await world.getPrisma();
const player = await prisma.player.findUnique({
where: { id: parseInt(playerId) },
include: { user: true }
});
if (player && player.user) {
const userId = player.user.id;
(world.user as any).id = userId;
await prisma.user.update({
where: { id: userId },
data: { role: 'club_admin' }
});
console.log(`🌍 Assigned club_admin role to user: ${userId}`);
await world.page.goto(`${world.baseURL}/`);
await world.page.waitForLoadState('domcontentloaded');
await world.page.waitForTimeout(1000);
} }
}
console.log(`🌍 Club admin created: ${credentials.email}`);
}); });
/** /**
@@ -584,7 +566,7 @@ When('I go to the tournament schedule page', async function () {
const tournamentId = world.tournament?.id || 1; const tournamentId = world.tournament?.id || 1;
const url = `${world.baseURL}/admin/tournaments/${tournamentId}/schedule?t=${Date.now()}`; const url = `${world.baseURL}/admin/tournaments/${tournamentId}/schedule?t=${Date.now()}`;
await world.page.goto(url); await world.page.goto(url);
await world.page.waitForLoadState('domcontentloaded'); await world.page.waitForLoadState('networkidle');
// Wait for ScheduleDisplay client component to hydrate // Wait for ScheduleDisplay client component to hydrate
await world.page.waitForTimeout(2000); await world.page.waitForTimeout(2000);
}); });
@@ -110,7 +110,7 @@ When('I go back', async function () {
When('I refresh the page', async function () { When('I refresh the page', async function () {
console.log('🌍 About to refresh page from URL:', world.page.url()); console.log('🌍 About to refresh page from URL:', world.page.url());
await world.page.reload({ waitUntil: 'load' }); await world.page.reload({ waitUntil: 'networkidle' });
console.log('🌍 Page refreshed, new URL:', world.page.url()); console.log('🌍 Page refreshed, new URL:', world.page.url());
// Wait extra time for full render // Wait extra time for full render
await world.page.waitForTimeout(2000); await world.page.waitForTimeout(2000);
@@ -191,7 +191,7 @@ When('I click the {string} link', async function (linkText: string) {
// Wait for navigation to complete // Wait for navigation to complete
try { try {
await world.page.waitForLoadState('domcontentloaded', { timeout: 10000 }); await world.page.waitForLoadState('networkidle', { timeout: 10000 });
} catch { } catch {
console.log(`🌍 Networkidle not reached, continuing`); console.log(`🌍 Networkidle not reached, continuing`);
} }
@@ -653,7 +653,7 @@ Then('I should see round {int} matchups', async function (roundNumber: number) {
}); });
Then('I should see {int} rounds', async function (expectedRounds: number) { Then('I should see {int} rounds', async function (expectedRounds: number) {
await world.page.waitForLoadState('domcontentloaded'); await world.page.waitForLoadState('networkidle');
await world.page.waitForTimeout(2000); await world.page.waitForTimeout(2000);
const roundHeaders = await world.page.locator('h3:has-text("Round")').count(); const roundHeaders = await world.page.locator('h3:has-text("Round")').count();
expect(roundHeaders).toBe(expectedRounds); expect(roundHeaders).toBe(expectedRounds);
@@ -690,7 +690,7 @@ Then('I should be on the match result entry page', async function () {
// View As Role Steps // View As Role Steps
When('I view the navigation', async function () { When('I view the navigation', async function () {
await world.page.waitForLoadState('domcontentloaded'); await world.page.waitForLoadState('networkidle');
await world.page.waitForTimeout(1000); await world.page.waitForTimeout(1000);
console.log('🌍 Viewing navigation'); console.log('🌍 Viewing navigation');
}); });
@@ -750,7 +750,7 @@ Then('I should not see the viewing as banner', async function () {
When('I go to the tournament detail page', async function () { When('I go to the tournament detail page', async function () {
const tournamentId = world.tournament?.id || 1; const tournamentId = world.tournament?.id || 1;
await world.page.goto(`${world.baseURL}/admin/tournaments/${tournamentId}`); await world.page.goto(`${world.baseURL}/admin/tournaments/${tournamentId}`);
await world.page.waitForLoadState('domcontentloaded'); await world.page.waitForLoadState('networkidle');
await world.page.waitForTimeout(500); await world.page.waitForTimeout(500);
console.log(`🌍 Navigated to tournament detail page: ${tournamentId}`); console.log(`🌍 Navigated to tournament detail page: ${tournamentId}`);
}); });
@@ -1,73 +0,0 @@
import { Given, After } from '@cucumber/cucumber';
import { world } from '../support/world';
Given('there are top players in the system', async function () {
const prisma = await world.getPrisma();
const timestamp = Date.now();
for (let i = 0; i < 3; i++) {
await prisma.player.create({
data: {
name: `Home Test Player ${timestamp} ${i + 1}`,
normalizedName: `home_test_player_${timestamp}_${i + 1}`.toLowerCase(),
currentElo: 2000 - i * 10,
gamesPlayed: 10,
wins: 7,
},
});
}
});
Given('there is a club president', async function () {
const prisma = await world.getPrisma();
const timestamp = Date.now();
await prisma.user.create({
data: {
email: `president-${timestamp}@example.com`,
name: `Club President ${timestamp}`,
role: 'club_admin',
},
});
});
Given('there is a recent tournament', async function () {
const prisma = await world.getPrisma();
const timestamp = Date.now();
const tournament = await prisma.event.create({
data: {
name: `Recent Tournament ${timestamp}`,
eventType: 'tournament',
eventDate: new Date(Date.now() + 86400000),
status: 'completed',
},
});
const p1 = await prisma.player.create({
data: { name: `HP1 ${timestamp}`, normalizedName: `hp1_${timestamp}`.toLowerCase(), currentElo: 1500 },
});
const p2 = await prisma.player.create({
data: { name: `HP2 ${timestamp}`, normalizedName: `hp2_${timestamp}`.toLowerCase(), currentElo: 1480 },
});
const p3 = await prisma.player.create({
data: { name: `HP3 ${timestamp}`, normalizedName: `hp3_${timestamp}`.toLowerCase(), currentElo: 1450 },
});
const p4 = await prisma.player.create({
data: { name: `HP4 ${timestamp}`, normalizedName: `hp4_${timestamp}`.toLowerCase(), currentElo: 1420 },
});
await prisma.match.create({
data: {
eventId: tournament.id,
player1P1Id: p1.id,
player1P2Id: p2.id,
player2P1Id: p3.id,
player2P2Id: p4.id,
team1Score: 10,
team2Score: 5,
status: 'completed',
playedAt: new Date(),
},
});
});
+11 -12
View File
@@ -14,17 +14,22 @@ setDefaultTimeout(30000);
// Global browser instance // Global browser instance
let browser: Browser; let browser: Browser;
// Load environment file (gitignored, contains dev database URL) // Load environment files
const envPath = path.resolve(process.cwd(), '.env');
const envDevPath = path.resolve(process.cwd(), '.env.development'); const envDevPath = path.resolve(process.cwd(), '.env.development');
if (fs.existsSync(envPath)) {
require('dotenv').config({ path: envPath });
}
if (fs.existsSync(envDevPath)) { if (fs.existsSync(envDevPath)) {
require('dotenv').config({ path: envDevPath }); require('dotenv').config({ path: envDevPath, override: true });
} }
// Database safety check - prevent tests from running against production // Database safety check - prevent tests from running against production
function isProductionDatabase(): boolean { function isProductionDatabase(): boolean {
const dbUrl = process.env.DATABASE_URL || ''; const dbUrl = process.env.DATABASE_URL || '';
return dbUrl.includes('euchre_camp') && !dbUrl.includes('_dev') && !dbUrl.includes('_ci') && !dbUrl.includes('test'); return dbUrl.includes('euchre_camp') && !dbUrl.includes('_dev') && !dbUrl.includes('test');
} }
if (isProductionDatabase()) { if (isProductionDatabase()) {
@@ -130,8 +135,7 @@ After(async function () {
where: { where: {
OR: [ OR: [
{ name: { startsWith: 'Test Tournament' } }, { name: { startsWith: 'Test Tournament' } },
{ name: { startsWith: 'Test Schedule Tournament' } }, { name: { startsWith: 'Test Schedule Tournament' } }
{ name: { startsWith: 'Recent Tournament' } },
] ]
}, },
select: { id: true } select: { id: true }
@@ -172,9 +176,7 @@ After(async function () {
{ name: { startsWith: 'Tournament Player' } }, { name: { startsWith: 'Tournament Player' } },
{ name: { startsWith: 'Schedule Player' } }, { name: { startsWith: 'Schedule Player' } },
{ name: { startsWith: 'Test Player' } }, { name: { startsWith: 'Test Player' } },
{ name: { startsWith: 'Test Activity Player' } }, { name: { startsWith: 'Test Activity Player' } }
{ name: { startsWith: 'Home Test Player' } },
{ name: { startsWith: 'HP' } },
] ]
} }
}); });
@@ -182,10 +184,7 @@ After(async function () {
// Delete test users // Delete test users
await prisma.user.deleteMany({ await prisma.user.deleteMany({
where: { where: {
OR: [ email: { startsWith: 'cucumber-' }
{ email: { startsWith: 'cucumber-' } },
{ email: { startsWith: 'president-' } },
]
} }
}); });
+41 -56
View File
@@ -10,87 +10,74 @@ import fs from 'fs';
import path from 'path'; import path from 'path';
test.describe.skip('Elo Rating Updates', () => { test.describe('Elo Rating Updates', () => {
test.beforeAll(async () => { test.beforeAll(async () => {
// Clean up any existing test data // Clean up any existing test data
const playerIds = await getEloTestPlayerIds();
// First delete matches that reference players // First delete matches that reference players
await prisma.match.deleteMany({ await prisma.match.deleteMany({
where: { where: {
OR: [ OR: [
{ player1P1Id: { in: playerIds } }, { player1P1Id: { in: await getEloTestPlayerIds() } },
{ player1P2Id: { in: playerIds } }, { player1P2Id: { in: await getEloTestPlayerIds() } },
{ player2P1Id: { in: playerIds } }, { player2P1Id: { in: await getEloTestPlayerIds() } },
{ player2P2Id: { in: playerIds } }, { player2P2Id: { in: await getEloTestPlayerIds() } },
] ]
} }
}); });
// Then delete partnerships that reference players // Then delete partnerships
await prisma.partnershipStat.deleteMany({ await prisma.partnershipStat.deleteMany({
where: { where: {
OR: [ OR: [
{ player1Id: { in: playerIds } }, { player1Id: { in: await getEloTestPlayerIds() } },
{ player2Id: { in: playerIds } }, { player2Id: { in: await getEloTestPlayerIds() } },
] ]
} }
}); });
// Then delete event participants that reference players
await prisma.eventParticipant.deleteMany({
where: {
playerId: { in: playerIds }
}
});
// Finally delete players // Finally delete players
await prisma.player.deleteMany({ await prisma.player.deleteMany({
where: { where: {
id: { in: playerIds } name: {
startsWith: 'Elo Test'
}
} }
}); });
}); });
test.afterAll(async () => { test.afterAll(async () => {
// Clean up test data // Clean up test data
const playerIds = await getEloTestPlayerIds();
// First delete matches that reference players // First delete matches that reference players
await prisma.match.deleteMany({ await prisma.match.deleteMany({
where: { where: {
OR: [ OR: [
{ player1P1Id: { in: playerIds } }, { player1P1Id: { in: await getEloTestPlayerIds() } },
{ player1P2Id: { in: playerIds } }, { player1P2Id: { in: await getEloTestPlayerIds() } },
{ player2P1Id: { in: playerIds } }, { player2P1Id: { in: await getEloTestPlayerIds() } },
{ player2P2Id: { in: playerIds } }, { player2P2Id: { in: await getEloTestPlayerIds() } },
] ]
} }
}); });
// Then delete partnerships that reference players // Then delete partnerships
await prisma.partnershipStat.deleteMany({ await prisma.partnershipStat.deleteMany({
where: { where: {
OR: [ OR: [
{ player1Id: { in: playerIds } }, { player1Id: { in: await getEloTestPlayerIds() } },
{ player2Id: { in: playerIds } }, { player2Id: { in: await getEloTestPlayerIds() } },
] ]
} }
}); });
// Then delete event participants that reference players
await prisma.eventParticipant.deleteMany({
where: {
playerId: { in: playerIds }
}
});
// Finally delete players // Finally delete players
await prisma.player.deleteMany({ await prisma.player.deleteMany({
where: { where: {
id: { in: playerIds } name: {
startsWith: 'Elo Test'
}
} }
}); });
await prisma.$disconnect();
}); });
async function getEloTestPlayerIds(): Promise<number[]> { async function getEloTestPlayerIds(): Promise<number[]> {
@@ -107,11 +94,10 @@ test.describe.skip('Elo Rating Updates', () => {
test('Elo rating updates after match upload', async ({ page }) => { test('Elo rating updates after match upload', async ({ page }) => {
// Step 1: Create test players with known initial ratings // Step 1: Create test players with known initial ratings
const ts = Date.now();
const player1 = await prisma.player.create({ const player1 = await prisma.player.create({
data: { data: {
name: `Elo Test Player 1 ${ts}`, name: 'Elo Test Player 1',
normalizedName: `elo_test_player_1_${ts}`, normalizedName: 'elo test player 1',
currentElo: 1500, currentElo: 1500,
gamesPlayed: 0, gamesPlayed: 0,
wins: 0, wins: 0,
@@ -121,8 +107,8 @@ test.describe.skip('Elo Rating Updates', () => {
const player2 = await prisma.player.create({ const player2 = await prisma.player.create({
data: { data: {
name: `Elo Test Player 2 ${ts}`, name: 'Elo Test Player 2',
normalizedName: `elo_test_player_2_${ts}`, normalizedName: 'elo test player 2',
currentElo: 1500, currentElo: 1500,
gamesPlayed: 0, gamesPlayed: 0,
wins: 0, wins: 0,
@@ -132,8 +118,8 @@ test.describe.skip('Elo Rating Updates', () => {
const player3 = await prisma.player.create({ const player3 = await prisma.player.create({
data: { data: {
name: `Elo Test Player 3 ${ts}`, name: 'Elo Test Player 3',
normalizedName: `elo_test_player_3_${ts}`, normalizedName: 'elo test player 3',
currentElo: 1500, currentElo: 1500,
gamesPlayed: 0, gamesPlayed: 0,
wins: 0, wins: 0,
@@ -143,8 +129,8 @@ test.describe.skip('Elo Rating Updates', () => {
const player4 = await prisma.player.create({ const player4 = await prisma.player.create({
data: { data: {
name: `Elo Test Player 4 ${ts}`, name: 'Elo Test Player 4',
normalizedName: `elo_test_player_4_${ts}`, normalizedName: 'elo test player 4',
currentElo: 1500, currentElo: 1500,
gamesPlayed: 0, gamesPlayed: 0,
wins: 0, wins: 0,
@@ -253,13 +239,13 @@ test.describe.skip('Elo Rating Updates', () => {
// Wait for page to load and tournaments to be fetched // Wait for page to load and tournaments to be fetched
await page.waitForLoadState('domcontentloaded'); await page.waitForLoadState('domcontentloaded');
await page.waitForTimeout(500); await page.waitForTimeout(2000);
// Wait for tournament dropdown to be ready // Wait for tournament dropdown to be ready
await page.waitForSelector('select#tournament', { timeout: 3000 }); await page.waitForSelector('select#tournament', { timeout: 5000 });
// Wait a bit for tournaments to load // Wait a bit for tournaments to load
await page.waitForTimeout(500); await page.waitForTimeout(2000);
// Select the tournament manually // Select the tournament manually
const tournamentSelect = await page.locator('select#tournament'); const tournamentSelect = await page.locator('select#tournament');
@@ -315,7 +301,7 @@ ${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
// Wait for upload to complete // Wait for upload to complete
await page.waitForTimeout(1000); await page.waitForTimeout(3000);
// Check for any error messages // Check for any error messages
const uploadContentAfter = await page.content(); const uploadContentAfter = await page.content();
@@ -328,11 +314,11 @@ ${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player
// Navigate back to upload page for second match // Navigate back to upload page for second match
await page.goto('/admin/matches/upload'); await page.goto('/admin/matches/upload');
await page.waitForLoadState('domcontentloaded'); await page.waitForLoadState('domcontentloaded');
await page.waitForTimeout(500); await page.waitForTimeout(2000);
// Re-select the tournament for the second upload // Re-select the tournament for the second upload
await page.waitForSelector('select#tournament', { timeout: 3000 }); await page.waitForSelector('select#tournament', { timeout: 5000 });
await page.waitForTimeout(200); // Wait for tournaments to load await page.waitForTimeout(1000); // Wait for tournaments to load
const tournamentSelect2 = await page.locator('select#tournament'); const tournamentSelect2 = await page.locator('select#tournament');
const currentSelection = await tournamentSelect2.inputValue(); const currentSelection = await tournamentSelect2.inputValue();
@@ -351,10 +337,10 @@ ${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player
await page.setInputFiles('input[type="file"]', tmpFile2); await page.setInputFiles('input[type="file"]', tmpFile2);
await page.waitForTimeout(500); await page.waitForTimeout(500);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForTimeout(500); await page.waitForTimeout(2000);
fs.unlinkSync(tmpFile2); fs.unlinkSync(tmpFile2);
await page.waitForTimeout(500); await page.waitForTimeout(2000);
// Verify ratings after multiple matches // Verify ratings after multiple matches
const updatedPlayer1 = await prisma.player.findUnique({ const updatedPlayer1 = await prisma.player.findUnique({
@@ -383,11 +369,10 @@ ${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player
test('Elo ratings are visible on player profile', async ({ page }) => { test('Elo ratings are visible on player profile', async ({ page }) => {
// Create a test player // Create a test player
const ts = Date.now();
const player = await prisma.player.create({ const player = await prisma.player.create({
data: { data: {
name: `Elo Test Profile Player ${ts}`, name: 'Elo Test Profile Player',
normalizedName: `elo_test_profile_player_${ts}`, normalizedName: 'elo test profile player',
currentElo: 1750, currentElo: 1750,
gamesPlayed: 50, gamesPlayed: 50,
wins: 30, wins: 30,
+7 -8
View File
@@ -12,7 +12,6 @@
import { test, expect } from '@playwright/test'; import { test, expect } from '@playwright/test';
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
function getTestCredentials() { function getTestCredentials() {
@@ -36,11 +35,11 @@ test.describe.serial('Epic 1: User Logout', () => {
testName = credentials.name; testName = credentials.name;
// Create test user via API with proper origin header // Create test user via API with proper origin header
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, { const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Origin': BASE_URL, 'Origin': 'http://localhost:3000',
'X-Requested-With': 'XMLHttpRequest' 'X-Requested-With': 'XMLHttpRequest'
}, },
body: JSON.stringify({ body: JSON.stringify({
@@ -93,7 +92,7 @@ test.describe.serial('Epic 1: User Logout', () => {
test('Logout button appears in navigation when logged in', async ({ page }) => { test('Logout button appears in navigation when logged in', async ({ page }) => {
// Login first // Login first
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
// Wait for page to load // Wait for page to load
await page.waitForLoadState('domcontentloaded'); await page.waitForLoadState('domcontentloaded');
@@ -133,7 +132,7 @@ test.describe.serial('Epic 1: User Logout', () => {
await page.waitForLoadState('domcontentloaded'); await page.waitForLoadState('domcontentloaded');
// Wait a moment for the navigation component to update // Wait a moment for the navigation component to update
await page.waitForTimeout(200); await page.waitForTimeout(1000);
// Debug: Check what's on the page // Debug: Check what's on the page
const pageContent = await page.content(); const pageContent = await page.content();
@@ -157,7 +156,7 @@ test.describe.serial('Epic 1: User Logout', () => {
test('Logout clears session and redirects to home', async ({ page }) => { test('Logout clears session and redirects to home', async ({ page }) => {
// Login first // Login first
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
@@ -181,7 +180,7 @@ test.describe.serial('Epic 1: User Logout', () => {
test('After logout, protected pages redirect to login', async ({ page }) => { test('After logout, protected pages redirect to login', async ({ page }) => {
// Login first // Login first
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
@@ -201,7 +200,7 @@ test.describe.serial('Epic 1: User Logout', () => {
await page.waitForURL('**/auth/login**', { timeout: 10000 }); await page.waitForURL('**/auth/login**', { timeout: 10000 });
// Try to access admin page // Try to access admin page
await page.goto('/admin'); await page.goto('http://localhost:3000/admin');
// Should redirect to login // Should redirect to login
await expect(page).toHaveURL(/.*auth\/login.*/); await expect(page).toHaveURL(/.*auth\/login.*/);
+2 -2
View File
@@ -19,7 +19,7 @@ import { test, expect } from '@playwright/test';
test.describe.skip('Epic 1: Password Reset (Not Implemented)', () => { test.describe.skip('Epic 1: Password Reset (Not Implemented)', () => {
test('Forgot password link exists on login page', async ({ page }) => { test('Forgot password link exists on login page', async ({ page }) => {
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
// Check for forgot password link // Check for forgot password link
await expect(page.locator('a[href*="password-reset"]')).toBeVisible(); await expect(page.locator('a[href*="password-reset"]')).toBeVisible();
@@ -29,7 +29,7 @@ test.describe.skip('Epic 1: Password Reset (Not Implemented)', () => {
test('Password reset page exists but is not functional', async ({ page }) => { test('Password reset page exists but is not functional', async ({ page }) => {
// Note: The link exists but the page may not be implemented // Note: The link exists but the page may not be implemented
// This test documents the current state // This test documents the current state
await page.goto('/auth/password-reset'); await page.goto('http://localhost:3000/auth/password-reset');
// Check if page loads (may show "not implemented" message) // Check if page loads (may show "not implemented" message)
await expect(page.locator('body')).toBeVisible(); await expect(page.locator('body')).toBeVisible();
+6 -6
View File
@@ -51,7 +51,7 @@ test.describe.serial('Epic 1: User Registration', () => {
}); });
test('Registration page exists and loads', async ({ page }) => { test('Registration page exists and loads', async ({ page }) => {
await page.goto('/auth/register'); await page.goto('http://localhost:3000/auth/register');
// Check for registration form elements // Check for registration form elements
await expect(page.locator('input[name="name"]')).toBeVisible(); await expect(page.locator('input[name="name"]')).toBeVisible();
@@ -61,7 +61,7 @@ test.describe.serial('Epic 1: User Registration', () => {
}); });
test('Registration with valid data creates account', async ({ page }) => { test('Registration with valid data creates account', async ({ page }) => {
await page.goto('/auth/register'); await page.goto('http://localhost:3000/auth/register');
// Wait for page to load // Wait for page to load
await page.waitForLoadState('domcontentloaded'); await page.waitForLoadState('domcontentloaded');
@@ -89,7 +89,7 @@ test.describe.serial('Epic 1: User Registration', () => {
}); });
// Wait a moment for JavaScript to be ready // Wait a moment for JavaScript to be ready
await page.waitForTimeout(200); await page.waitForTimeout(1000);
// Submit form // Submit form
const [response] = await Promise.all([ const [response] = await Promise.all([
@@ -122,7 +122,7 @@ test.describe.serial('Epic 1: User Registration', () => {
}); });
test('Registration with duplicate email fails', async ({ page }) => { test('Registration with duplicate email fails', async ({ page }) => {
await page.goto('/auth/register'); await page.goto('http://localhost:3000/auth/register');
// Fill registration form with existing email // Fill registration form with existing email
await page.fill('input[name="name"]', testName); await page.fill('input[name="name"]', testName);
@@ -147,7 +147,7 @@ test.describe.serial('Epic 1: User Registration', () => {
}); });
test('Registration with weak password fails', async ({ page }) => { test('Registration with weak password fails', async ({ page }) => {
await page.goto('/auth/register'); await page.goto('http://localhost:3000/auth/register');
// Fill registration form with weak password // Fill registration form with weak password
await page.fill('input[name="name"]', testName); await page.fill('input[name="name"]', testName);
@@ -162,7 +162,7 @@ test.describe.serial('Epic 1: User Registration', () => {
}); });
test('Auto-created player profile is linked to user', async ({ page }) => { test('Auto-created player profile is linked to user', async ({ page }) => {
await page.goto('/auth/register'); await page.goto('http://localhost:3000/auth/register');
const profileEmail = `profile-${Date.now()}@example.com`; const profileEmail = `profile-${Date.now()}@example.com`;
const profileName = 'Profile Test User'; const profileName = 'Profile Test User';
+5 -5
View File
@@ -15,17 +15,17 @@ import { test, expect } from '@playwright/test';
test.describe('Epic 3: Rankings Page', () => { test.describe('Epic 3: Rankings Page', () => {
test('Rankings page loads and displays rankings table', async ({ page }) => { test('Rankings page loads and displays rankings table', async ({ page }) => {
await page.goto('/rankings'); await page.goto('http://localhost:3000/rankings');
// Check page title or heading - use .first() since page may have both h1 and h2 // Check page title or heading
await expect(page.locator('h1, h2').first()).toContainText(/rankings?/i); await expect(page.locator('h1, h2')).toContainText(/rankings?/i);
// Check for rankings table // Check for rankings table
await expect(page.locator('table')).toBeVisible(); await expect(page.locator('table')).toBeVisible();
}); });
test('Rankings table displays player columns', async ({ page }) => { test('Rankings table displays player columns', async ({ page }) => {
await page.goto('/rankings'); await page.goto('http://localhost:3000/rankings');
// Check for expected column headers // Check for expected column headers
const table = page.locator('table'); const table = page.locator('table');
@@ -38,7 +38,7 @@ test.describe('Epic 3: Rankings Page', () => {
test('Rankings page is publicly accessible (no login required)', async ({ page }) => { test('Rankings page is publicly accessible (no login required)', async ({ page }) => {
// Navigate directly to rankings without logging in // Navigate directly to rankings without logging in
await page.goto('/rankings'); await page.goto('http://localhost:3000/rankings');
// Page should load without redirecting to login // Page should load without redirecting to login
await expect(page).toHaveURL(/.*rankings.*/); await expect(page).toHaveURL(/.*rankings.*/);
+13 -24
View File
@@ -13,7 +13,6 @@
import { test, expect } from '@playwright/test'; import { test, expect } from '@playwright/test';
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
function getTestCredentials() { function getTestCredentials() {
@@ -25,7 +24,7 @@ function getTestCredentials() {
}; };
} }
test.describe.skip('Epic 4: Tournament Creation', () => { test.describe.serial('Epic 4: Tournament Creation', () => {
let testEmail: string; let testEmail: string;
let testPassword: string; let testPassword: string;
let testName: string; let testName: string;
@@ -37,11 +36,11 @@ test.describe.skip('Epic 4: Tournament Creation', () => {
testName = credentials.name; testName = credentials.name;
// Create admin user via API // Create admin user via API
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, { const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Origin': BASE_URL 'Origin': 'http://localhost:3000'
}, },
body: JSON.stringify({ body: JSON.stringify({
email: testEmail, email: testEmail,
@@ -83,16 +82,16 @@ test.describe.skip('Epic 4: Tournament Creation', () => {
test('Tournament creation page exists and loads', async ({ page }) => { test('Tournament creation page exists and loads', async ({ page }) => {
// Login first // Login first
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
// Wait for redirect to admin or player profile (indicates successful login) // Wait for redirect to admin or player profile (indicates successful login)
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to new tournament page // Navigate to new tournament page
await page.goto('/admin/tournaments/new'); await page.goto('http://localhost:3000/admin/tournaments/new');
// Check for form // Check for form
await expect(page.locator('form')).toBeVisible(); await expect(page.locator('form')).toBeVisible();
@@ -100,44 +99,34 @@ test.describe.skip('Epic 4: Tournament Creation', () => {
test('Tournament form has required fields', async ({ page }) => { test('Tournament form has required fields', async ({ page }) => {
// Login first // Login first
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
// Wait for redirect to admin or player profile (indicates successful login) // Wait for redirect to admin or player profile (indicates successful login)
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
await page.goto('/admin/tournaments/new'); await page.goto('http://localhost:3000/admin/tournaments/new');
// Wait for step 1 form to load // Check for required fields
await page.waitForSelector('input[name="name"]', { timeout: 5000 });
// Check for required fields on Step 1
await expect(page.locator('input[name="name"]')).toBeVisible(); await expect(page.locator('input[name="name"]')).toBeVisible();
await expect(page.locator('select[name="format"]')).toBeVisible(); await expect(page.locator('select[name="format"]')).toBeVisible();
// Fill in the required name field first so Next actually advances
await page.fill('input[name="name"]', 'Test Tournament');
// Step through to Step 2 to check for submit button (only appears after clicking Next)
await page.click('button:has-text("Next")');
await page.waitForSelector('button[type="submit"]', { timeout: 5000 });
await expect(page.locator('button[type="submit"]')).toBeVisible(); await expect(page.locator('button[type="submit"]')).toBeVisible();
}); });
test('Create tournament with valid data', async ({ page }) => { test('Create tournament with valid data', async ({ page }) => {
// Login first // Login first
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
// Wait for redirect to admin or player profile (indicates successful login) // Wait for redirect to admin or player profile (indicates successful login)
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to new tournament page // Navigate to new tournament page
await page.goto('/admin/tournaments/new'); await page.goto('http://localhost:3000/admin/tournaments/new');
const tournamentName = `Test Tournament ${Date.now()}`; const tournamentName = `Test Tournament ${Date.now()}`;
+6 -9
View File
@@ -98,23 +98,20 @@ async function createTestUsers(config: FullConfig) {
console.log('Submitting registration form...'); console.log('Submitting registration form...');
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
try { try {
await page.waitForResponse(response => await page.waitForResponse(response =>
response.url().includes('/api/auth/sign-up/email') && response.status() === 200, response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
{ timeout: 5000 } { timeout: 10000 }
); );
console.log('Sign-up API call successful'); console.log('Sign-up API call successful');
} catch { } catch {
console.log('Sign-up API call failed or timed out'); console.log('Sign-up API call failed or timed out');
} }
await page.waitForTimeout(500); await page.waitForTimeout(2000);
await context.storageState({ path: authFile }); await context.storageState({ path: authFile });
console.log(`Created and authenticated test user: ${testEmail}`); console.log(`Created and authenticated test user: ${testEmail}`);
// Clear session so admin registration doesn't get redirected
await context.clearCookies();
const adminTimestamp = timestamp + 1; const adminTimestamp = timestamp + 1;
const adminEmail = `setup-admin-${adminTimestamp}@example.com`; const adminEmail = `setup-admin-${adminTimestamp}@example.com`;
const adminPassword = 'AdminPassword123!'; const adminPassword = 'AdminPassword123!';
@@ -133,14 +130,14 @@ try {
try { try {
await page.waitForResponse(response => await page.waitForResponse(response =>
response.url().includes('/api/auth/sign-up/email') && response.status() === 200, response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
{ timeout: 5000 } { timeout: 10000 }
); );
console.log('Admin sign-up API call successful'); console.log('Admin sign-up API call successful');
} catch { } catch {
console.log('Admin sign-up API call failed or timed out'); console.log('Admin sign-up API call failed or timed out');
} }
await page.waitForTimeout(500); await page.waitForTimeout(2000);
const prisma = createPrismaClient(); const prisma = createPrismaClient();
const user = await prisma.user.findUnique({ where: { email: adminEmail } }); const user = await prisma.user.findUnique({ where: { email: adminEmail } });
@@ -159,7 +156,7 @@ try {
await page.waitForLoadState('domcontentloaded'); await page.waitForLoadState('domcontentloaded');
console.log('Admin page loaded:', page.url()); console.log('Admin page loaded:', page.url());
await page.waitForTimeout(500); await page.waitForTimeout(2000);
await page.reload(); await page.reload();
await page.waitForLoadState('domcontentloaded'); await page.waitForLoadState('domcontentloaded');
console.log('Page reloaded'); console.log('Page reloaded');
-26
View File
@@ -24,14 +24,6 @@ const TEST_PATTERNS = {
'%TestUser%', '%TestUser%',
'%Cucumber%', '%Cucumber%',
'%Config Admin%', '%Config Admin%',
'%Elo Test%',
'%Dedupe%',
'%Whitespace%',
'%Aggregate%',
'%Tournament Player%',
'%Schedule Player%',
'%Test Activity Player%',
'%HP%',
], ],
events: [ events: [
'%Test%', '%Test%',
@@ -39,21 +31,12 @@ const TEST_PATTERNS = {
'%Recent%', '%Recent%',
'%Test Tournament%', '%Test Tournament%',
'%Cucumber%', '%Cucumber%',
'%Elo Test%',
'%Schedule%',
], ],
users: [ users: [
'%test%', '%test%',
'%setup%', '%setup%',
'%cucumber%', '%cucumber%',
'%TestUser%', '%TestUser%',
'%logout-test%',
'%admin-%',
'%config-admin%',
'%schedule-admin%',
'%nine-part-test%',
'%tour-admin-%',
'%president-%',
] ]
}; };
@@ -113,18 +96,9 @@ async function cleanupTestRecords(prisma: PrismaClient) {
const eventWhere = buildLikeClause(TEST_PATTERNS.events); const eventWhere = buildLikeClause(TEST_PATTERNS.events);
const userWhere = buildEmailLikeClause(TEST_PATTERNS.users); const userWhere = buildEmailLikeClause(TEST_PATTERNS.users);
await prisma.$executeRawUnsafe(`DELETE FROM elo_snapshots WHERE "playerId" IN (SELECT id FROM players WHERE (${playerWhere}));`);
await prisma.$executeRawUnsafe(`DELETE FROM partnership_games WHERE "player1Id" IN (SELECT id FROM players WHERE (${playerWhere}));`);
await prisma.$executeRawUnsafe(`DELETE FROM partnership_stats WHERE "player1Id" IN (SELECT id FROM players WHERE (${playerWhere}));`);
await prisma.$executeRawUnsafe(`DELETE FROM event_participants WHERE "eventId" IN (SELECT id FROM events WHERE (${eventWhere}));`);
await prisma.$executeRawUnsafe(`DELETE FROM tournament_rounds WHERE "eventId" IN (SELECT id FROM events WHERE (${eventWhere}));`);
await prisma.$executeRawUnsafe(`DELETE FROM bracket_matchups WHERE "eventId" IN (SELECT id FROM events WHERE (${eventWhere}));`);
await prisma.$executeRawUnsafe(`DELETE FROM events WHERE (${eventWhere});`); await prisma.$executeRawUnsafe(`DELETE FROM events WHERE (${eventWhere});`);
console.log('Deleted test events'); console.log('Deleted test events');
await prisma.$executeRawUnsafe(`DELETE FROM elo_ratings WHERE "playerId" IN (SELECT id FROM players WHERE (${playerWhere}));`);
await prisma.$executeRawUnsafe(`DELETE FROM glicko2_ratings WHERE "playerId" IN (SELECT id FROM players WHERE (${playerWhere}));`);
await prisma.$executeRawUnsafe(`DELETE FROM open_skill_ratings WHERE "playerId" IN (SELECT id FROM players WHERE (${playerWhere}));`);
await prisma.$executeRawUnsafe(`DELETE FROM players WHERE (${playerWhere});`); await prisma.$executeRawUnsafe(`DELETE FROM players WHERE (${playerWhere});`);
console.log('Deleted test players'); console.log('Deleted test players');
+110
View File
@@ -0,0 +1,110 @@
import { test, expect } from '@playwright/test'
import { prisma } from '@/lib/prisma'
test.describe('Home Page', () => {
const createdIds = {
players: [] as number[],
events: [] as number[],
matches: [] as number[],
users: [] as string[],
}
test.afterEach(async () => {
await prisma.match.deleteMany({ where: { id: { in: createdIds.matches } } })
await prisma.event.deleteMany({ where: { id: { in: createdIds.events } } })
await prisma.player.deleteMany({ id: { in: createdIds.players } })
await prisma.user.deleteMany({ where: { id: { in: createdIds.users } } })
createdIds.players = []
createdIds.events = []
createdIds.matches = []
createdIds.users = []
})
test('displays top 10 players section', async ({ page }) => {
const timestamp = Date.now()
for (let i = 0; i < 3; i++) {
const player = await prisma.player.create({
data: {
name: `Home Test Player ${timestamp} ${i + 1}`,
normalizedName: `home_test_player_${timestamp}_${i + 1}`.toLowerCase(),
currentElo: 2000 - i * 10,
gamesPlayed: 10,
wins: 7,
},
})
createdIds.players.push(player.id)
}
await page.goto('/')
await expect(page.locator('text=Top 10 Players')).toBeVisible()
await expect(
page.locator(`a:has-text("Home Test Player ${timestamp} 1")`)
).toBeVisible()
})
test('displays club president section', async ({ page }) => {
const timestamp = Date.now()
const user = await prisma.user.create({
data: {
email: `president-${timestamp}@example.com`,
name: `Club President ${timestamp}`,
role: 'club_admin',
},
})
createdIds.users.push(user.id)
await page.goto('/')
await expect(page.locator('text=Club President')).toBeVisible()
})
test('displays most recent tournament section', async ({ page }) => {
const timestamp = Date.now()
const tournament = await prisma.event.create({
data: {
name: `Recent Tournament ${timestamp}`,
eventType: 'tournament',
eventDate: new Date(Date.now() + 86400000),
status: 'completed',
},
})
createdIds.events.push(tournament.id)
const p1 = await prisma.player.create({
data: { name: `HP1 ${timestamp}`, normalizedName: `hp1_${timestamp}`.toLowerCase(), currentElo: 1500 },
})
const p2 = await prisma.player.create({
data: { name: `HP2 ${timestamp}`, normalizedName: `hp2_${timestamp}`.toLowerCase(), currentElo: 1480 },
})
const p3 = await prisma.player.create({
data: { name: `HP3 ${timestamp}`, normalizedName: `hp3_${timestamp}`.toLowerCase(), currentElo: 1450 },
})
const p4 = await prisma.player.create({
data: { name: `HP4 ${timestamp}`, normalizedName: `hp4_${timestamp}`.toLowerCase(), currentElo: 1420 },
})
createdIds.players.push(p1.id, p2.id, p3.id, p4.id)
const match = await prisma.match.create({
data: {
eventId: tournament.id,
player1P1Id: p1.id,
player1P2Id: p2.id,
player2P1Id: p3.id,
player2P2Id: p4.id,
team1Score: 10,
team2Score: 5,
status: 'completed',
playedAt: new Date(),
},
})
createdIds.matches.push(match.id)
await page.goto('/')
await expect(page.locator('text=Most Recent Tournament')).toBeVisible()
await expect(page.locator(`text=Recent Tournament ${timestamp}`)).toBeVisible()
})
})
+21 -22
View File
@@ -13,7 +13,6 @@
import { test, expect } from '@playwright/test'; import { test, expect } from '@playwright/test';
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
function getTestCredentials() { function getTestCredentials() {
const timestamp = Date.now(); const timestamp = Date.now();
@@ -24,7 +23,7 @@ function getTestCredentials() {
}; };
} }
test.describe.skip('Issue #7: Schedule Tab', () => { test.describe.serial('Issue #7: Schedule Tab', () => {
let testEmail: string; let testEmail: string;
let testPassword: string; let testPassword: string;
let tournamentId: number; let tournamentId: number;
@@ -35,11 +34,11 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
testPassword = credentials.password; testPassword = credentials.password;
// Create admin user via API // Create admin user via API
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, { const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Origin: BASE_URL, Origin: 'http://localhost:3000',
}, },
body: JSON.stringify({ body: JSON.stringify({
email: testEmail, email: testEmail,
@@ -129,30 +128,30 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
test('Schedule tab link exists on tournament detail page', async ({ page }) => { test('Schedule tab link exists on tournament detail page', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to tournament detail // Navigate to tournament detail
await page.goto(`/admin/tournaments/${tournamentId}`); await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}`);
// Check Schedule tab link exists - use button since page uses buttons for tabs // Check Schedule tab link exists
const scheduleLink = page.locator('button', { hasText: 'Schedule' }); const scheduleLink = page.locator('a', { hasText: 'Schedule' });
await expect(scheduleLink).toBeVisible(); await expect(scheduleLink).toBeVisible();
}); });
test('Schedule page loads with no schedule message', async ({ page }) => { test('Schedule page loads with no schedule message', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to schedule page // Navigate to schedule page
await page.goto(`/admin/tournaments/${tournamentId}/schedule`); await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
// Check page content // Check page content
await expect(page.locator('h1')).toContainText('Tournament Schedule'); await expect(page.locator('h1')).toContainText('Tournament Schedule');
@@ -162,20 +161,20 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
test('Generate schedule creates rounds and matchups', async ({ page }) => { test('Generate schedule creates rounds and matchups', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to schedule page // Navigate to schedule page
await page.goto(`/admin/tournaments/${tournamentId}/schedule`); await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
// Click generate schedule // Click generate schedule
await page.click('button:has-text("Generate Schedule")'); await page.click('button:has-text("Generate Schedule")');
// Wait for success message or page reload // Wait for success message or page reload
await page.waitForTimeout(500); await page.waitForTimeout(3000);
// Verify rounds were created in database // Verify rounds were created in database
const rounds = await prisma.tournamentRound.findMany({ const rounds = await prisma.tournamentRound.findMany({
@@ -192,14 +191,14 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
test('Schedule page displays generated rounds and matchups', async ({ page }) => { test('Schedule page displays generated rounds and matchups', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to schedule page // Navigate to schedule page
await page.goto(`/admin/tournaments/${tournamentId}/schedule`); await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
// Check that rounds are displayed // Check that rounds are displayed
await expect(page.locator('text=Round 1')).toBeVisible(); await expect(page.locator('text=Round 1')).toBeVisible();
@@ -214,15 +213,15 @@ test.describe.skip('Issue #7: Schedule Tab', () => {
test('Schedule API returns rounds with matchups', async ({ page }) => { test('Schedule API returns rounds with matchups', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Call the schedule API // Call the schedule API
const response = await page.request.get( const response = await page.request.get(
`/api/tournaments/${tournamentId}/schedule` `http://localhost:3000/api/tournaments/${tournamentId}/schedule`
); );
expect(response.ok()).toBe(true); expect(response.ok()).toBe(true);
+103
View File
@@ -8,6 +8,109 @@
import { test, expect } from '@playwright/test' import { test, expect } from '@playwright/test'
test.describe('Smoke Test: EuchreCamp Application', () => { test.describe('Smoke Test: EuchreCamp Application', () => {
test.describe('Admin Panel Navigation', () => {
test('should navigate to admin dashboard', async ({ page }) => {
await page.goto('/admin')
// Admin dashboard should be visible
await expect(page.locator('text=Admin')).toBeVisible()
})
test('should navigate to matches admin page', async ({ page }) => {
await page.goto('/admin/matches')
await expect(page.locator('text=Match Management')).toBeVisible()
})
test('should navigate to players admin page', async ({ page }) => {
await page.goto('/admin/players')
await expect(page.locator('text=Player Management')).toBeVisible()
})
test('should navigate to users admin page', async ({ page }) => {
await page.goto('/admin/users')
await expect(page.locator('text=User Management')).toBeVisible()
})
})
test.describe('Match Management', () => {
test('should display matches page', async ({ page }) => {
await page.goto('/admin/matches')
// Verify page header is visible
await expect(page.locator('text=Match Management')).toBeVisible()
// Page should load successfully - verify either table or empty state is present
const hasTable = await page.locator('table').count().then(c => c > 0)
const hasEmptyState = await page.locator('text=/no matches|No matches/').count().then(c => c > 0)
// At least one should be present
expect(hasTable || hasEmptyState).toBeTruthy()
})
test('should have delete button for matches when matches exist', async ({ page }) => {
await page.goto('/admin/matches')
// Check if delete buttons exist in the table
const deleteButtons = page.locator('button:has-text("Delete")')
const count = await deleteButtons.count()
// Table might be empty, but if there are matches, delete buttons should exist
if (count > 0) {
await expect(page.locator('text=Actions')).toBeVisible()
}
})
})
test.describe('Player Management', () => {
test('should display players table', async ({ page }) => {
await page.goto('/admin/players')
await expect(page.locator('table')).toBeVisible()
await expect(page.locator('text=Player Name')).toBeVisible()
await expect(page.locator('text=Current Elo')).toBeVisible()
await expect(page.locator('text=Actions')).toBeVisible()
})
test('should have edit and delete buttons for players', async ({ page }) => {
await page.goto('/admin/players')
// At minimum, verify the Actions column exists
await expect(page.locator('text=Actions')).toBeVisible()
})
test('should allow editing player name', async ({ page }) => {
await page.goto('/admin/players')
// Click edit on first player
const editButton = page.locator('button:has-text("Edit")').first()
if (await editButton.isVisible()) {
await editButton.click()
// Verify edit modal appears
await expect(page.locator('text=Edit Player Name')).toBeVisible()
// Close modal
await page.click('text=Cancel')
await expect(page.locator('text=Edit Player Name')).not.toBeVisible()
}
})
})
test.describe('User Management', () => {
test('should display users page', async ({ page }) => {
await page.goto('/admin/users')
// Page should load with either a table or "no users" message
const hasTable = await page.locator('table').isVisible().catch(() => false)
const hasNoUsers = await page.locator('text=No users found').isVisible().catch(() => false)
// At least one of these should be true
expect(hasTable || hasNoUsers).toBeTruthy()
// Verify page header is visible
await expect(page.locator('text=User Management')).toBeVisible()
})
test('should have create user link', async ({ page }) => {
await page.goto('/admin/users')
// Check for the main create user link (with green button styling)
const createLink = page.locator('a.bg-green-600:has-text("Create User")')
await expect(createLink).toBeVisible()
})
})
test.describe('Public Pages', () => { test.describe('Public Pages', () => {
test('should display rankings page', async ({ page }) => { test('should display rankings page', async ({ page }) => {
await page.goto('/rankings') await page.goto('/rankings')
+18 -20
View File
@@ -7,7 +7,6 @@
import { test, expect } from '@playwright/test'; import { test, expect } from '@playwright/test';
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
function getTestCredentials() { function getTestCredentials() {
const timestamp = Date.now(); const timestamp = Date.now();
@@ -18,7 +17,7 @@ function getTestCredentials() {
}; };
} }
test.describe.skip('Issue #22: Team Configuration', () => { test.describe.serial('Issue #22: Team Configuration', () => {
let testEmail: string; let testEmail: string;
let testPassword: string; let testPassword: string;
let tournamentId: number; let tournamentId: number;
@@ -29,11 +28,11 @@ test.describe.skip('Issue #22: Team Configuration', () => {
testPassword = credentials.password; testPassword = credentials.password;
// Create admin user via API // Create admin user via API
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, { const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Origin: BASE_URL, Origin: 'http://localhost:3000',
}, },
body: JSON.stringify({ body: JSON.stringify({
email: testEmail, email: testEmail,
@@ -78,14 +77,14 @@ test.describe.skip('Issue #22: Team Configuration', () => {
test('Tournament creation form shows team configuration options', async ({ page }) => { test('Tournament creation form shows team configuration options', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to tournament creation // Navigate to tournament creation
await page.goto('/admin/tournaments/new'); await page.goto('http://localhost:3000/admin/tournaments/new');
// Select Round Robin format // Select Round Robin format
await page.selectOption('select[name="format"]', 'round_robin'); await page.selectOption('select[name="format"]', 'round_robin');
@@ -101,14 +100,14 @@ test.describe.skip('Issue #22: Team Configuration', () => {
test('Create tournament with permanent teams', async ({ page }) => { test('Create tournament with permanent teams', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to tournament creation // Navigate to tournament creation
await page.goto('/admin/tournaments/new'); await page.goto('http://localhost:3000/admin/tournaments/new');
// Fill in tournament details // Fill in tournament details
await page.fill('input[name="name"]', `Test Tournament ${Date.now()}`); await page.fill('input[name="name"]', `Test Tournament ${Date.now()}`);
@@ -126,8 +125,7 @@ test.describe.skip('Issue #22: Team Configuration', () => {
const playerName3 = `Player ${Date.now() + 2}`; const playerName3 = `Player ${Date.now() + 2}`;
const playerName4 = `Player ${Date.now() + 3}`; const playerName4 = `Player ${Date.now() + 3}`;
// Create first player - wait for search input to appear first // Create first player
await page.waitForSelector('input[placeholder*="Search"]', { timeout: 5000 });
await page.fill('input[placeholder*="Search"]', playerName1); await page.fill('input[placeholder*="Search"]', playerName1);
await page.waitForTimeout(500); await page.waitForTimeout(500);
await page.click(`text=+ Create "${playerName1}" as new player`); await page.click(`text=+ Create "${playerName1}" as new player`);
@@ -177,14 +175,14 @@ test.describe.skip('Issue #22: Team Configuration', () => {
test('Create tournament with variable teams and partner rotation', async ({ page }) => { test('Create tournament with variable teams and partner rotation', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to tournament creation // Navigate to tournament creation
await page.goto('/admin/tournaments/new'); await page.goto('http://localhost:3000/admin/tournaments/new');
// Fill in tournament details // Fill in tournament details
await page.fill('input[name="name"]', `Variable Teams Tournament ${Date.now()}`); await page.fill('input[name="name"]', `Variable Teams Tournament ${Date.now()}`);
@@ -239,11 +237,11 @@ test.describe.skip('Issue #22: Team Configuration', () => {
test('Edit tournament team configuration', async ({ page }) => { test('Edit tournament team configuration', async ({ page }) => {
// First create a tournament with default settings // First create a tournament with default settings
const createResponse = await fetch(`${BASE_URL}/api/tournaments`, { const createResponse = await fetch('http://localhost:3000/api/tournaments', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Origin: BASE_URL, Origin: 'http://localhost:3000',
}, },
body: JSON.stringify({ body: JSON.stringify({
name: `Edit Test Tournament ${Date.now()}`, name: `Edit Test Tournament ${Date.now()}`,
@@ -255,14 +253,14 @@ test.describe.skip('Issue #22: Team Configuration', () => {
tournamentId = createData.tournament.id; tournamentId = createData.tournament.id;
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to edit tournament page // Navigate to edit tournament page
await page.goto(`/admin/tournaments/${tournamentId}/edit`); await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/edit`);
// Check that team configuration section is visible // Check that team configuration section is visible
await expect(page.locator('text=Team Configuration')).toBeVisible(); await expect(page.locator('text=Team Configuration')).toBeVisible();
-3
View File
@@ -1,3 +0,0 @@
export const BASE_URL = process.env.BASE_URL || (process.env.CI
? 'https://euchre-ci.notsosm.art'
: 'http://localhost:3000');
+13 -14
View File
@@ -18,7 +18,6 @@
import { test, expect } from '@playwright/test'; import { test, expect } from '@playwright/test';
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
function getTestCredentials() { function getTestCredentials() {
const timestamp = Date.now(); const timestamp = Date.now();
@@ -29,7 +28,7 @@ function getTestCredentials() {
}; };
} }
test.describe.skip('Tournament with 10 Participants and Variable Team Durability', () => { test.describe.serial('Tournament with 10 Participants and Variable Team Durability', () => {
let testEmail: string; let testEmail: string;
let testPassword: string; let testPassword: string;
let tournamentId: number; let tournamentId: number;
@@ -42,11 +41,11 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
const timestamp = Date.now(); const timestamp = Date.now();
// Create admin user via API // Create admin user via API
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, { const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Origin: BASE_URL, Origin: 'http://localhost:3000',
}, },
body: JSON.stringify({ body: JSON.stringify({
email: testEmail, email: testEmail,
@@ -103,14 +102,14 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
test('Tournament creation form shows variable team durability options', async ({ page }) => { test('Tournament creation form shows variable team durability options', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to tournament creation // Navigate to tournament creation
await page.goto('/admin/tournaments/new'); await page.goto('http://localhost:3000/admin/tournaments/new');
// Select Round Robin format // Select Round Robin format
await page.selectOption('select[name="format"]', 'round_robin'); await page.selectOption('select[name="format"]', 'round_robin');
@@ -133,14 +132,14 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
test('Create tournament with 10 participants, variable teams, and minimize_repeat', async ({ page }) => { test('Create tournament with 10 participants, variable teams, and minimize_repeat', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to tournament creation // Navigate to tournament creation
await page.goto('/admin/tournaments/new'); await page.goto('http://localhost:3000/admin/tournaments/new');
// Fill in tournament details // Fill in tournament details
const tournamentName = `9 Participant Variable Tournament ${Date.now()}`; const tournamentName = `9 Participant Variable Tournament ${Date.now()}`;
@@ -189,7 +188,7 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
await page.click('button:has-text("Add")'); await page.click('button:has-text("Add")');
// Wait for the player to be added and UI to update // Wait for the player to be added and UI to update
await page.waitForTimeout(200); await page.waitForTimeout(1000);
} }
// Verify 10 players are added // Verify 10 players are added
@@ -239,7 +238,7 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
test('Schedule generation for 10 participants creates correct number of matchups', async ({ page }) => { test('Schedule generation for 10 participants creates correct number of matchups', async ({ page }) => {
// Navigate to Matchups tab (formerly Teams tab) // Navigate to Matchups tab (formerly Teams tab)
// The test is already authenticated via the chromium-admin project // The test is already authenticated via the chromium-admin project
await page.goto(`/admin/tournaments/${tournamentId}`); await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}`);
// Wait for page to load and data to be fetched // Wait for page to load and data to be fetched
await page.waitForLoadState('domcontentloaded'); await page.waitForLoadState('domcontentloaded');
@@ -281,14 +280,14 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
test('Schedule displays correct matchups for 10 participants', async ({ page }) => { test('Schedule displays correct matchups for 10 participants', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to Schedule tab // Navigate to Schedule tab
await page.goto(`/admin/tournaments/${tournamentId}/schedule`); await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
// Verify rounds are displayed // Verify rounds are displayed
await expect(page.locator('text=Round 1')).toBeVisible(); await expect(page.locator('text=Round 1')).toBeVisible();
@@ -305,14 +304,14 @@ test.describe.skip('Tournament with 10 Participants and Variable Team Durability
test('Matchup generation with minimize_repeat creates varied partnerships', async ({ page }) => { test('Matchup generation with minimize_repeat creates varied partnerships', async ({ page }) => {
// Login // Login
await page.goto('/auth/login'); await page.goto('http://localhost:3000/auth/login');
await page.fill('input[name="email"]', testEmail); await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword); await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]'); await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 }); await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
// Navigate to Schedule tab // Navigate to Schedule tab
await page.goto(`/admin/tournaments/${tournamentId}/schedule`); await page.goto(`http://localhost:3000/admin/tournaments/${tournamentId}/schedule`);
// Get all matchups from the database to verify partnership variety // Get all matchups from the database to verify partnership variety
const matchups = await prisma.bracketMatchup.findMany({ const matchups = await prisma.bracketMatchup.findMany({
@@ -11,54 +11,11 @@
import { test, expect } from '@playwright/test'; import { test, expect } from '@playwright/test';
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
const BASE_URL = process.env.CI ? 'https://euchre-ci.notsosm.art' : 'http://localhost:3000';
function getTestCredentials() { test.describe('Tournament Edit - allowTies functionality', () => {
const timestamp = Date.now();
return {
email: `allowties-admin-${timestamp}@example.com`,
password: 'AdminPassword123!',
name: `AllowTies Admin ${timestamp}`,
};
}
test.describe.skip('Tournament Edit - allowTies functionality', () => {
let tournamentId: number; let tournamentId: number;
let testEmail: string;
let testPassword: string;
test.beforeAll(async () => { test.beforeAll(async () => {
// Create admin user via API
const credentials = getTestCredentials();
testEmail = credentials.email;
testPassword = credentials.password;
const response = await fetch(`${BASE_URL}/api/auth/sign-up/email`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Origin: BASE_URL,
},
body: JSON.stringify({
email: testEmail,
password: testPassword,
name: credentials.name,
}),
});
console.log('allowTies test user creation response:', response.status);
// Update user to club_admin role
const user = await prisma.user.findUnique({
where: { email: testEmail },
});
if (user) {
await prisma.user.update({
where: { id: user.id },
data: { role: 'club_admin' },
});
}
// Create a test tournament for editing // Create a test tournament for editing
const tournament = await prisma.event.create({ const tournament = await prisma.event.create({
data: { data: {
@@ -68,7 +25,6 @@ test.describe.skip('Tournament Edit - allowTies functionality', () => {
status: 'planned', status: 'planned',
allowTies: false, allowTies: false,
targetScore: 5, targetScore: 5,
ownerId: user?.id,
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
}, },
@@ -81,28 +37,16 @@ test.describe.skip('Tournament Edit - allowTies functionality', () => {
if (tournamentId) { if (tournamentId) {
await prisma.event.delete({ await prisma.event.delete({
where: { id: tournamentId }, where: { id: tournamentId },
}).catch(() => {}); });
}
// Clean up user
const user = await prisma.user.findUnique({ where: { email: testEmail } });
if (user) {
await prisma.user.delete({ where: { id: user.id } });
} }
}); });
test('should display allowTies checkbox on edit form @chromium-admin', async ({ page }) => { test('should display allowTies checkbox on edit form @chromium-admin', async ({ page }) => {
// Login first
await page.goto('/auth/login');
await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
// Navigate to tournament edit page // Navigate to tournament edit page
await page.goto(`/admin/tournaments/${tournamentId}/edit`); await page.goto(`/admin/tournaments/${tournamentId}/edit`);
// Wait for form to load - edit page shows "Edit Tournament" heading // Wait for form to load
await expect(page.locator('text=Edit Tournament')).toBeVisible({ timeout: 5000 }); await expect(page.locator('text=Tournament Name')).toBeVisible();
// Check that allowTies checkbox exists // Check that allowTies checkbox exists
const allowTiesCheckbox = page.locator('input[name="allowTies"]'); const allowTiesCheckbox = page.locator('input[name="allowTies"]');
@@ -111,18 +55,11 @@ test.describe.skip('Tournament Edit - allowTies functionality', () => {
}); });
test('should save allowTies when toggled to true @chromium-admin', async ({ page }) => { test('should save allowTies when toggled to true @chromium-admin', async ({ page }) => {
// Login first
await page.goto('/auth/login');
await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
// Navigate to tournament edit page // Navigate to tournament edit page
await page.goto(`/admin/tournaments/${tournamentId}/edit`); await page.goto(`/admin/tournaments/${tournamentId}/edit`);
// Wait for form to load // Wait for form to load
await expect(page.locator('text=Edit Tournament')).toBeVisible({ timeout: 5000 }); await expect(page.locator('text=Tournament Name')).toBeVisible();
// Toggle allowTies checkbox // Toggle allowTies checkbox
const allowTiesCheckbox = page.locator('input[name="allowTies"]'); const allowTiesCheckbox = page.locator('input[name="allowTies"]');
@@ -150,18 +87,11 @@ test.describe.skip('Tournament Edit - allowTies functionality', () => {
data: { allowTies: true }, data: { allowTies: true },
}); });
// Login first
await page.goto('/auth/login');
await page.fill('input[name="email"]', testEmail);
await page.fill('input[name="password"]', testPassword);
await page.click('button[type="submit"]');
await page.waitForURL(/\/(admin|players)/, { timeout: 5000 });
// Navigate to tournament edit page // Navigate to tournament edit page
await page.goto(`/admin/tournaments/${tournamentId}/edit`); await page.goto(`/admin/tournaments/${tournamentId}/edit`);
// Wait for form to load // Wait for form to load
await expect(page.locator('text=Edit Tournament')).toBeVisible({ timeout: 5000 }); await expect(page.locator('text=Tournament Name')).toBeVisible();
// Verify checkbox is checked // Verify checkbox is checked
const allowTiesCheckbox = page.locator('input[name="allowTies"]'); const allowTiesCheckbox = page.locator('input[name="allowTies"]');
+2 -2
View File
@@ -259,12 +259,12 @@ deploy-prod version:
docker compose pull app && \ docker compose pull app && \
docker compose up -d app && \ docker compose up -d app && \
echo "Waiting for production site to be healthy..." && \ echo "Waiting for production site to be healthy..." && \
for i in {1..6}; do \ for i in {1..30}; do \
if curl -sf https://euchre.notsosm.art/api/health > /dev/null 2>&1; then \ if curl -sf https://euchre.notsosm.art/api/health > /dev/null 2>&1; then \
echo "✅ Production successfully deployed with version {{version}}"; \ echo "✅ Production successfully deployed with version {{version}}"; \
exit 0; \ exit 0; \
fi; \ fi; \
sleep 15; \ sleep 0.5; \
done && \ done && \
echo "❌ Production deployment failed - health check timed out"; \ echo "❌ Production deployment failed - health check timed out"; \
docker compose logs app; \ docker compose logs app; \
-10473
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "euchre_camp", "name": "euchre_camp",
"version": "0.1.21", "version": "0.1.20",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "NEXT_PUBLIC_GIT_COMMIT=$(git rev-parse --short HEAD) next dev", "dev": "NEXT_PUBLIC_GIT_COMMIT=$(git rev-parse --short HEAD) next dev",
+9 -7
View File
@@ -4,12 +4,16 @@ export default defineConfig({
testDir: './e2e', testDir: './e2e',
timeout: 30000, timeout: 30000,
expect: { expect: {
timeout: 2000 timeout: 5000
}, },
// Run tests in parallel for speed - database isolation is per-test via unique data // Run tests sequentially to avoid database conflicts
fullyParallel: true, fullyParallel: false,
// Use multiple workers in CI to speed up test execution // Fail the build on CI if you accidentally left test.only in the source code.
workers: process.env.CI ? 10 : 1, forbidOnly: !!process.env.CI,
// Retry on CI only.
retries: process.env.CI ? 1 : 0,
// Use 2 workers in CI for parallel project execution; 1 locally
workers: process.env.CI ? 2 : 1,
// Reporter to use // Reporter to use
reporter: 'html', reporter: 'html',
// Global setup and teardown // Global setup and teardown
@@ -39,7 +43,6 @@ export default defineConfig({
storageState: 'playwright/.auth/user.json', storageState: 'playwright/.auth/user.json',
}, },
dependencies: ['setup'], dependencies: ['setup'],
testIgnore: ['**/admin-*.test.ts'],
}, },
// Admin user project // Admin user project
{ {
@@ -60,7 +63,6 @@ export default defineConfig({
storageState: undefined, storageState: undefined,
}, },
dependencies: ['setup'], dependencies: ['setup'],
testIgnore: ['**/admin-*.test.ts'],
}, },
], ],
// Run your local dev server before starting the tests // Run your local dev server before starting the tests
+3 -1
View File
@@ -47,7 +47,9 @@ describe('getSession', () => {
}) })
it('returns null when an error occurs', async () => { it('returns null when an error occurs', async () => {
mockFetch.mockRejectedValue(new Error('Network error')) mockFetch.mockImplementation(async () => {
throw new Error('Network error')
})
const result = await getSession() const result = await getSession()
+17 -25
View File
@@ -3,37 +3,17 @@
* Tests the allowTies field is properly saved when updating tournaments * Tests the allowTies field is properly saved when updating tournaments
*/ */
import { describe, it, expect, mock, beforeEach,} from 'bun:test'; import { describe, it, expect, mock, beforeEach, afterAll } from 'bun:test';
// Create mock functions at module level // Create mock functions at module level
const eventFindUniqueMock = mock(async () => ({})); const eventFindUniqueMock = mock(async () => ({}));
const eventUpdateMock = mock(async () => ({})); const eventUpdateMock = mock(async () => ({}));
const userFindUniqueMock = mock(async () => ({ const canManageTournamentMock = mock(async () => ({ allowed: true }));
id: 'admin-1', const canDeleteTournamentMock = mock(async () => ({ allowed: true }));
email: 'admin@example.com',
role: 'club_admin',
emailVerified: false,
name: null,
image: null,
playerId: null,
createdAt: new Date(),
updatedAt: new Date(),
}));
// Mock auth-simple to return a valid session // Mock prisma first
mock.module('@/lib/auth-simple', () => ({
getSession: mock(async () => ({
user: { id: 'admin-1', email: 'admin@example.com' },
session: { token: 'test', expiresAt: new Date() }
})),
}));
// Mock prisma with user and event
mock.module('@/lib/prisma', () => ({ mock.module('@/lib/prisma', () => ({
prisma: { prisma: {
user: {
findUnique: userFindUniqueMock,
},
event: { event: {
findUnique: eventFindUniqueMock, findUnique: eventFindUniqueMock,
update: eventUpdateMock, update: eventUpdateMock,
@@ -41,6 +21,17 @@ mock.module('@/lib/prisma', () => ({
}, },
})); }));
// Mock the permissions module
mock.module('@/lib/permissions', () => ({
canManageTournament: canManageTournamentMock,
canDeleteTournament: canDeleteTournamentMock,
}));
// Cleanup after all tests in this file
afterAll(() => {
mock.restore('module');
});
// Import the route handler after mocking // Import the route handler after mocking
import { PUT } from '@/app/api/tournaments/[id]/route'; import { PUT } from '@/app/api/tournaments/[id]/route';
import { prisma } from '@/lib/prisma'; import { prisma } from '@/lib/prisma';
@@ -50,7 +41,8 @@ describe('Tournament Update API', () => {
// Clear all mock history before each test // Clear all mock history before each test
eventFindUniqueMock.mockClear(); eventFindUniqueMock.mockClear();
eventUpdateMock.mockClear(); eventUpdateMock.mockClear();
userFindUniqueMock.mockClear(); canManageTournamentMock.mockClear();
canDeleteTournamentMock.mockClear();
}); });
it('should update allowTies field when provided', async () => { it('should update allowTies field when provided', async () => {