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:

LOGIN_USER=admin
LOGIN_PASSWORD=password

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
    try:
        dotenv.load_dotenv(conf)
        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:

self.driver.find_element_by_xpath(self.user_field_xpath).send_keys(self.username)
self.driver.find_element_by_xpath(self.pass_field_xpath).send_keys(self.password)

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!

Advertisements