Vedro: How To Define Environment Variables
Tags: python, testing, vedro
Published: 2023-11-25 12:43:32

Environment variables are key-value pairs used in software development to store configuration settings and control application behavior without hardcoding them into the source code. They facilitate managing different configurations across various environments, like local development or staging. This approach is essential for maintaining clean, adaptable code and securely handling sensitive information, such as API keys.

In automated testing, environment variables facilitate seamless transitions between various settings or data sources, simplifying the testing process across multiple deployment environments.

## Scenario: Retrieving a List of Asteroids

To illustrate, consider a [Vedro](https://vedro.io/) test scenario that requires loading an API key from an environment variable to access an endpoint providing a list of asteroids. For this example, the focus will be on the [NeoWs](https://api.nasa.gov/) (Near Earth Object Web Service) provided by NASA, which offers comprehensive data about near-Earth asteroids.

Here's the basic structure of a Vedro test scenario:

```python
import httpx
import vedro

class Scenario(vedro.Scenario):
    subject = "retrieve list of asteroids"

    def given_api_key(self):
        # API key will be loaded from environment variable
        self.api_key = <load from env>

    def when_user_retrieves_asteroids(self):
        # Make a GET request to the NeoWs API
        self.response = httpx.get("https://api.nasa.gov/neo/rest/v1/feed", params={
            "api_key": self.api_key
        })

    def then_it_should_return_success_response(self):
        # Assert the success of the response
        assert self.response.status_code == 200
```

## Reading Environment Variables in Python

To read environment variables in Python, you can use the [os](https://docs.python.org/3/library/os.html#os.environ) module. Here's how to modify the `given_api_key` method to load the API key from an environment variable:

```python
from os import environ

class Scenario(vedro.Scenario):
    subject = "retrieve list of asteroids"

    def given_api_key(self):
        self.api_key = environ.get("API_KEY")

    ...
```

## Defining Environment Variables

There are two primary ways to define environment variables for tests.

### Method 1: Directly in the Environment

Define environment variables directly in the shell:

```shell
$ export API_KEY="DEMO_KEY"
```

Then run tests:

```shell
$ vedro run
Scenarios
*
 ✔ retrieve list of asteroids

# 1 scenario, 1 passed, 0 failed, 0 skipped (1.79s)
```

### Method 2: Using a .env File

Alternatively, you can use a `.env` file:

```
API_KEY="DEMO_KEY"
```

Install the [python-dotenv](https://pypi.org/project/python-dotenv/) package to load variables from the `.env` file:

```shell
$ pip3 install python-dotenv
```

Then, load the environment variables in the `vedro.cfg.py`:

```python
import vedro
import vedro_allure_reporter
from dotenv import load_dotenv

load_dotenv(".env")


class Config(vedro.Config):

    class Plugins(vedro.Config.Plugins):

        class AllureReporter(vedro_allure_reporter.AllureReporter):
            enabled = True
```

> The configuration above includes the [Allure reporter plugin](https://pypi.org/project/vedro-allure-reporter/) for Vedro. This plugin generates comprehensive, interactive reports, enhancing test result visualization. For detailed integration instructions, refer to the blog post: [How to Integrate Vedro with Allure](https://dev.to/mickeystreicher/how-to-integrate-vedro-with-allure-3jkb).

Run tests again:

```shell
$ vedro run
Scenarios
*
 ✔ retrieve list of asteroids

# 1 scenario, 1 passed, 0 failed, 0 skipped (1.61s)
```

A significant advantage of using `.env` files in testing scenarios is their flexibility in managing multiple environment variables across different testing environments. For instance, separate env-files like `.env-local` for local development and `.env-staging` for staging environments can be used. This approach enables developers and testers to easily switch contexts without altering the code or the command line environment. 

Regardless of the chosen method, environment variables can be utilized anywhere in your tests: within the test itself, in contexts, or in a separate configuration file.