# Tekton Run Tests Task for Bakery-IA CI/CD
# This task runs tests on the source code

apiVersion: tekton.dev/v1beta1
kind: Task
metadata:
  name: run-tests
  namespace: {{ .Release.Namespace }}
  labels:
    app.kubernetes.io/name: {{ .Values.labels.app.name }}
    app.kubernetes.io/component: test
spec:
  workspaces:
    - name: source
      description: Workspace containing the source code
  params:
    - name: services
      type: string
      description: Comma-separated list of services to test
    - name: skip-tests
      type: string
      description: Skip tests if "true"
      default: "false"
  steps:
    - name: run-unit-tests
      image: python:3.11-slim
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        allowPrivilegeEscalation: false
        capabilities:
          drop:
            - ALL
        seccompProfile:
          type: RuntimeDefault
      workingDir: $(workspaces.source.path)
      script: |
        #!/bin/sh
        set -e

        echo "============================================"
        echo "Running Unit Tests"
        echo "Services: $(params.services)"
        echo "Skip tests: $(params.skip-tests)"
        echo "============================================"
        
        if [ "$(params.skip-tests)" = "true" ]; then
          echo "Skipping tests as requested"
          exit 0
        fi
        
        # Install dependencies if requirements file exists
        if [ -f "requirements.txt" ]; then
          pip install --no-cache-dir -r requirements.txt
        fi
        
        # Run unit tests
        python -m pytest tests/unit/ -v
        
        echo "Unit tests completed successfully"
      resources:
        limits:
          cpu: 1000m
          memory: 2Gi
        requests:
          cpu: 200m
          memory: 512Mi
    - name: run-integration-tests
      image: python:3.11-slim
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        allowPrivilegeEscalation: false
        capabilities:
          drop:
            - ALL
        seccompProfile:
          type: RuntimeDefault
      workingDir: $(workspaces.source.path)
      script: |
        #!/bin/sh
        set -e

        echo "============================================"
        echo "Running Integration Tests"
        echo "Services: $(params.services)"
        echo "============================================"
        
        if [ "$(params.skip-tests)" = "true" ]; then
          echo "Skipping integration tests as requested"
          exit 0
        fi
        
        # Run integration tests
        python -m pytest tests/integration/ -v
        
        echo "Integration tests completed successfully"
      resources:
        limits:
          cpu: 1000m
          memory: 2Gi
        requests:
          cpu: 200m
          memory: 512Mi