Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CI Pipeline through GH Actions #1157

Merged
merged 9 commits into from
Oct 6, 2024
66 changes: 66 additions & 0 deletions .github/workflows/unit_test_pipeline.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
name: TM1Py Integration Tests

on:
workflow_dispatch:
inputs:
environments:
description: 'JSON array of environments to test (e.g., ["tm1-11-onprem", "tm1-11-cloud"])'
required: true
default: '["tm1-11-onprem","tm1-11-cloud","tm1-12-mcsp"]'

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
environment: ${{ fromJson(github.event.inputs.environments) }}
environment: ${{ matrix.environment }}
steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'

- name: Install dependencies
run: |
pip install -e .[unit_test]

- name: Retrieve TM1 Connection Details
id: get-connection
run: echo "Retrieving TM1 connection details"
env:
TM1_CONNECTION: ${{ vars.TM1_CONNECTION }}
TM1_CONNECTION_SECRET: ${{ secrets.TM1_CONNECTION_SECRET }}

- name: Generate config.ini
run: |
python Tests/resources/generate_config.py
env:
TM1_CONNECTION: ${{ vars.TM1_CONNECTION }}
TM1_CONNECTION_SECRET: ${{ secrets.TM1_CONNECTION_SECRET }}

- name: Run tests
run: pytest Tests/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not for now, because the tests are not yet ready for this, but for the future: it would be good to have an option whether you want to run the tests in parallel or not.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is actually working like that right now, you can define that in the second parameter when you run the workflow:
image
In my case I have 3 environments defined:
image

  • tm1-11-onprem: a v11 instance we have running in an EC2 instance
  • tm1-11-cloud: a v11 instance hosted in IBM PA Cloud
  • tm1-12-mcsp: a v12 instance running as SaaS in AWS.

If I put those three, GH Actions will create 3 different and independent runners on the backend that run in parallel. Each of them will have its own config.ini file showing the TM1_CONNECTION and TM1_CONNECTION_SECRET from its own environment.

Below is a chart explaining the flow:

graph TD
    A[Workflow Dispatch] --> B[Input: Environments]
    B --> C[Parse Environments JSON]
    C --> D{Matrix Strategy}

    %% Parallel jobs for each environment
    D -->|tm1-11-onprem| E1
    D -->|tm1-11-cloud| E2
    D -->|tm1-12-mcsp| E3

    %% Independent Runner for tm1-11-onprem
    subgraph Runner: tm1-11-onprem
        E1[Job: Test tm1-11-onprem] --> F1[Checkout Code]
        F1 --> G1[Set Up Python]
        G1 --> H1[Install Dependencies]
        H1 --> I1[Retrieve TM1 Connection Details]
        I1 --> J1[Generate config.ini]
        J1 --> K1[Run Tests]
    end

    %% Independent Runner for tm1-11-cloud
    subgraph Runner: tm1-11-cloud
        E2[Job: Test tm1-11-cloud] --> F2[Checkout Code]
        F2 --> G2[Set Up Python]
        G2 --> H2[Install Dependencies]
        H2 --> I2[Retrieve TM1 Connection Details]
        I2 --> J2[Generate config.ini]
        J2 --> K2[Run Tests]
    end

    %% Independent Runner for tm1-12-mcsp
    subgraph Runner: tm1-12-mcsp
        E3[Job: Test tm1-12-mcsp] --> F3[Checkout Code]
        F3 --> G3[Set Up Python]
        G3 --> H3[Install Dependencies]
        H3 --> I3[Retrieve TM1 Connection Details]
        I3 --> J3[Generate config.ini]
        J3 --> K3[Run Tests]
    end
Loading

Copy link
Contributor

@onefloid onefloid Oct 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No I mean that the tests itself run in parallel with, e.g. pytest -n auto .\Tests\ElementService_test.py

Compare #1105

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh! I see, so you re-worked the ElementServce_test.py to be able to run independently from others?
Is this something we can do (or is already done) for other unit test cases? Or you are suggesting to run this one independently and the others sequentially?
Please feel free to create a PR against the yml and put this change in

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for being so unprecise. The clue is the -n option of pytest starts 1..n workers.
At the moment only a few tests can run with more than one worker. But in future it would be beneficial to specify how many workers should run in the pipeline.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Running tests in parallel is beneficial when you're working locally and want quick feedback IMO.

However, I'm concerned that parallel tests might occasionally fail due to potential race conditions or non-deterministic behavior in TM1. In the CI pipeline, I would prefer certainty over performance.

On the desktop, where you can easily re-run a failed test, I would prioritize performance over certainty.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the "Matrix Strategy" we should also get benefits of parallelization but the parallel executions should be isolated from one another.


- name: Upload test results
if: always()
uses: actions/upload-artifact@v3
with:
name: test-results-${{ matrix.environment }}
path: Tests/test-reports/

# Optional: Post results to PR
- name: Post comment to PR
if: always() && github.event_name == 'workflow_dispatch' && github.event.pull_request
uses: actions/github-script@v6
with:
script: |
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
body: 'Tests completed for environment: ${{ matrix.environment }}. Check artifacts for details.'
})
329 changes: 329 additions & 0 deletions Tests/_gh_README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,329 @@
# TM1Py GitHub Actions CI Pipeline

## Overview

We have implemented a continuous integration (CI) pipeline using GitHub Actions to automate the testing of TM1Py pull requests. This pipeline ensures that code changes are thoroughly tested across multiple TM1 environments before being merged. The key features of this new setup include:

- **Automated Testing**: Runs tests automatically for all defined TM1 environments whenever the workflow is triggered.
- **Dynamic Configuration**: Generates `config.ini` files dynamically based on environment-specific variables and secrets.
- **Parallel Execution**: Executes tests in parallel across different environments, ensuring efficient use of resources.
- **Secure Handling of Secrets**: Manages sensitive information securely using GitHub Environments and Secrets.

---

## Workflow Description

The new GitHub Actions workflow:

- **Identifies All Defined Environments**: Automatically attempts to run tests for all environments specified in the workflow matrix.
- **Checks for Required Variables**: Skips environments where the necessary variables (`TM1_CONNECTION` and `TM1_CONNECTION_SECRET`) are not defined.
- **Generates Configuration Files**: Creates a `config.ini` file for each environment using environment-specific variables and secrets.
- **Runs Tests in Isolation**: Executes tests for each environment in isolated runners to prevent interference.
- **Reports Results**: Uploads test results and, optionally, posts comments to pull requests with test outcomes.

---

## Architecture and Flow Diagram

Below is a flow diagram illustrating the CI pipeline's architecture and execution flow:

```mermaid
graph LR
A[Workflow Triggered] --> B{Environments in Matrix}
B --> |For Each Environment| C[Check for Required Variables]
C --> |Variables Present| D[Generate config.ini]
C --> |Variables Missing| E[Skip Job]
D --> F[Install Dependencies]
F --> G[Run Tests]
G --> H[Upload Test Results]
G --> I{Tests Passed?}
I --> |Yes| J[Optional: Post Comment to PR]
I --> |No| K[Fail the Job]
```

- **A**: The workflow is triggered manually or by an event (e.g., pull request).
- **B**: The workflow defines a matrix of environments to test.
- **C**: Each job checks if the required variables are present.
- **D**: If variables are present, `config.ini` is generated.
- **E**: If variables are missing, the job is skipped.
- **F**: Dependencies are installed, including any extras needed for testing.
- **G**: Tests are run using `pytest`.
- **H**: Test results are uploaded as artifacts.
- **I**: Checks if tests passed.
- **J**: Optionally posts a comment to the pull request with results.
- **K**: The job fails if tests did not pass.

---

## Repository Setup

### 1. Defining Environments

Create GitHub Environments for each TM1 instance/version you want to test against (there is no expected naming conversion):

- **Environments**:
- `tm1-11-onprem`
- `tm1-11-cloud`
- `tm1-12-mcsp`
- `tm1-12-paaas`
- `tm1-12-onprem`

### 2. Setting Environment Variables and Secrets

For each environment, define the necessary variables and secrets (naming on the variables MUST be respected):

- **Variables (`vars`)**:
- `TM1_CONNECTION`: A JSON string with non-sensitive connection parameters.

- **Secrets (`secrets`)**:
- `TM1_CONNECTION_SECRET`: A JSON string with sensitive connection parameters (e.g., passwords, API keys).

#### Sample Variables and Secrets for multiple types of environments

**Environment:** `tm1-11-onprem`

- **Variable (`TM1_CONNECTION`):**

```json
{
"address": "localhost",
"port": "8001",
"user": "admin",
"ssl": "true",
"session_context": "gh_unittest"
}
```

- **Secret (`TM1_CONNECTION_SECRET`):**

```json
{
"password": "apple"
}
```

**Environment:** `tm1-11-cloud`

- **Variable (`TM1_CONNECTION`):**

```json
{
"base_url": "https://server.planning-analytics.ibmcloud.com/tm1/api/tm1",
"user": "server01_tm1_automation",
"namespace": "LDAP",
"ssl": true,
"verify": true,
"async_requests_mode": true,
"session_context": "gh_unittest"
}
```

- **Secret (`TM1_CONNECTION_SECRET`):**

```json
{
"password": "<NonInteractiveAccountPwd>"
}
```

**Environment:** `tm1-12-mscp`

- **Variable (`TM1_CONNECTION`):**

```json
{
"base_url": "https://us-east-1.planninganalytics.saas.ibm.com/api/<TenantId>/v0/tm1/<DatabaseName>/",
"user": "apikey",
"password": "<TheActualApiKey>",
"async_requests_mode": true,
"ssl": true,
"verify": true,
"session_context": "gh_unittest"
}
```

- **Secret (`TM1_CONNECTION_SECRET`):**

```json
{
"password": "<TheActualApiKey>"
}
```

### 3. Workflow File

Create a workflow file `.github/workflows/tm1py-integration-tests.yml` with the following content:

```yaml
name: TM1Py Integration Tests

on:
workflow_dispatch:
inputs:
environments:
description: 'JSON array of environments to test (e.g., ["tm1-11-onprem", "tm1-11-cloud"])'
required: true
default: '["tm1-11-onprem","tm1-11-cloud","tm1-12-mcsp"]'

jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
environment: ${{ fromJson(github.event.inputs.environments) }}
environment: ${{ matrix.environment }}
steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'

- name: Install dependencies
run: |
pip install -e .[unit_test]

- name: Retrieve TM1 Connection Details
id: get-connection
run: echo "Retrieving TM1 connection details"
env:
TM1_CONNECTION: ${{ vars.TM1_CONNECTION }}
TM1_CONNECTION_SECRET: ${{ secrets.TM1_CONNECTION_SECRET }}

- name: Generate config.ini
run: |
python Tests/resources/generate_config.py
env:
TM1_CONNECTION: ${{ vars.TM1_CONNECTION }}
TM1_CONNECTION_SECRET: ${{ secrets.TM1_CONNECTION_SECRET }}

- name: Run tests
run: pytest Tests/

- name: Upload test results
if: always()
uses: actions/upload-artifact@v3
with:
name: test-results-${{ matrix.environment }}
path: Tests/test-reports/

# Optional: Post results to PR
- name: Post comment to PR
if: always() && github.event_name == 'workflow_dispatch' && github.event.pull_request
uses: actions/github-script@v6
with:
script: |
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
body: 'Tests completed for environment: ${{ matrix.environment }}. Check artifacts for details.'
})
```

---

## Parallel Execution of Multiple Environments

### How It Works

- **Matrix Strategy**: The workflow uses a matrix strategy to define jobs for each environment.
- **Parallel Jobs**: Each environment runs in its own job, which can execute in parallel with others.
- **Isolation**: Jobs are isolated from each other, each with its own runner and workspace.

### Ensuring Isolation

- **Separate Runners**: Each job runs on a separate virtual machine provided by GitHub Actions.
- **Unique Workspaces**: Each job has its own workspace and filesystem.
- **Environment Variables and Secrets**: Scoped to each job's environment, ensuring no cross-contamination.

### Benefits

- **Efficiency**: Tests for different environments run simultaneously, reducing total execution time.
- **No Interference**: Jobs do not interfere with each other, preventing conflicts in configuration files or resources.
- **Scalability**: Easily add or remove environments without affecting the workflow's structure.

---

## Additional Information

### Generating `config.ini`

A script `Tests/resources/generate_config.py` is used to create the `Tests/config.ini` file dynamically:

```python
import json
import os

tm1_connection = os.environ.get('TM1_CONNECTION')
tm1_connection_secret = os.environ.get('TM1_CONNECTION_SECRET')

config_content = '[tm1srv01]\n'

if tm1_connection:
conn_data = json.loads(tm1_connection)
for key, value in conn_data.items():
config_content += f"{key}={value}\n"

if tm1_connection_secret:
secret_data = json.loads(tm1_connection_secret)
for key, value in secret_data.items():
config_content += f"{key}={value}\n"

with open('Tests/config.ini', 'w') as f:
f.write(config_content)
```

### Updating `setup.py`

Ensure that all necessary dependencies are included:

```python
install_requires=[
'ijson',
'requests',
'pytz',
'requests_negotiate_sspi;platform_system=="Windows"',
'mdxpy>=1.3.1',
'networkx'],
extras_require={
"pandas": ["pandas"],
"dev": [
"pytest",
"pytest-xdist"
],
"unit_test": [
"pandas",
"pytest",
"pytest-xdist",
"python-dateutil"
]
},
```

### Security Considerations

- **Secrets Management**: Use GitHub Secrets to store sensitive information securely.
- **Access Control**: Secrets are only available to jobs that specify the corresponding environment.
- **Prevent Exposure**: Ensure that secrets are not printed in logs or exposed in any artifacts.

### Best Practices

- **Testing in Isolation**: Each test run is isolated to prevent interference between environments.
- **Resource Management**: Be mindful of GitHub Actions' concurrency limits and manage environments accordingly.
- **Documentation**: Keep documentation updated to reflect changes in the CI pipeline and testing procedures.

---

## Further Reading

- [GitHub Actions Documentation](https://docs.github.com/en/actions)
- [TM1Py Documentation](https://tm1py.readthedocs.io/en/latest/)
- [Python Packaging Guide](https://packaging.python.org/tutorials/packaging-projects/)
- [Secure Secrets Management in GitHub Actions](https://docs.github.com/en/actions/security-guides/encrypted-secrets)

---

**Note**: Remember to keep your repository's documentation up to date with these changes, and communicate with your team to ensure everyone is aware of the new testing procedures.
Loading