Often we need to authenticate users to run some test cases. In those cases we should never hardcode user’s credential in the test script. This could lead to a security issue. To resolve this problem we can keep the credentials in a separate file.

For this we need to install ‘dotenv’ and ‘os’.

For installing dotenv, run the following command in your terminal (for windows, try without ‘sudo’ and use Pycharm terminal).

sudo pip install -U python-dotenv

To learn detail about dotenv visit: https://pypi.python.org/pypi/python-dotenv

Now we need to create the credentials file and ‘Conf_Reader.py’ file to read from the credentials file.

In this post, the name of our credentials file is ‘login.credentials’.

Here is the login.credentials file content:


And the ‘Conf_Reader.py’ file is as bellow:

A simple conf reader.
For now, we just use dotenv and return a key.

import dotenv,os

def get_value(conf,key):
    # type: (object, object) -> object
    "Return the value in conf for a given key"
    value = None
        value = os.environ[key]
    except Exception,e:
        print 'Exception in get_value'
        print 'file: ',conf
        print 'key: ',key

    return value

Save those two files in the project directory.
Now, we need to use those files in our test script.

In the test script, first import the ‘Conf_Reader.py’ file:

import os, Conf_Reader

Now get the credentials from the ‘login.credentials’ file:

# Get the test account credentials from the .credentials file
credentials_file = os.path.join(os.path.dirname(__file__), 'login.credentials')
username = Conf_Reader.get_value(credentials_file, 'LOGIN_USER')
password = Conf_Reader.get_value(credentials_file, 'LOGIN_PASSWORD')

So, from now, we can use username and password variable for login:


NOTE: You can use the conf reader to parse more than just credentials. We find it very useful to put in a lot of test parameters that are usually hard coded within the script. This allows us to keep our scripts clean.

Hope this small piece of code will be helpful for you!