Don’t hardcode usernames and passwords in your test scripts

If your application needs to authenticate users, you need some way for your automation to know your credentials. You may be providing these credentials in the test script itself. But this could lead to a possible breach of security. E.g: We learnt that BrowserStack keeps logs of every line of code executed. So if you had hard coded your username and password in your test script, the logs will have a record of them. In this short post we will show you how to separate out the credentials into a separate file.

Here is the login.credentials file which stores the username and password

[email protected]
LOGIN_PASSWORD=test

You can use the following code snippet in your test script to read the credentials file and use the details in your test case.

import os,Conf_Reader
 
#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')

You want a peek into Conf_Reader.py? Here it is..

"""
A simple conf reader.
For now, we just use dotenv and return a key.
"""
 
import dotenv,os
 
def get_value(conf,key):
    "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

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!

6 thoughts on “Don’t hardcode usernames and passwords in your test scripts

  1. Hey..

    Just wanted to know. how this method is different from reading data from excel.??
    I had an another requirement actually.
    Currently I am reading data from excel but I want to read data from password protected excel.
    Can Conf_Reader, OS can do it???

  2. Hi Vrushali,
    I am SQA Engineer and I have done automation testing using Selenium. In this regard I need your some Consultancy. Would you please suggest me any add-on of jira for test automation Selenium Python.

  3. Hi, i am using python 3.7 but while install Conf_Reader in window 10 getting below error:
    can some one help
    pip install Conf_Reader
    Collecting Conf_Reader
    ERROR: Could not find a version that satisfies the requirement Conf_Reader (from versions: none)
    ERROR: No matching distribution found for Conf_Reader

    1. Hi Ganesh,
      Conf_Reader is not a python package to install with pip. Its just python file Conf_Reader.py with script mentioned in the blog.

Leave a Reply

Your email address will not be published. Required fields are marked *