Skip to content

Instantly share code, notes, and snippets.

@arifsuhan
Last active September 7, 2022 17:35
Show Gist options
  • Save arifsuhan/d38732f7c7ce960b18172dbc53b86c71 to your computer and use it in GitHub Desktop.
Save arifsuhan/d38732f7c7ce960b18172dbc53b86c71 to your computer and use it in GitHub Desktop.

An API Testing Framework: cmtestrunner

Steps Command
Create Virtual Env python3 -m venv [env_name]
Then activate the Env source [env_name]/bin/activate
Install dependency pip install -r requirements.txt
Create Django Project django-admin startproject [name]
Check pip packages pip list
Create utils directory python manage.py iwanttotest
Create App for test writing python manage.py startapp [name]
create boiler plate python manage.py createtest
-t [name for csv,url,methods]
-X [get/post]
-u [resource/relative api path]
-a [app name]
Test python manage.py test
Test python manage.py test [app_name]
Extra
Deactivate deactivate
Remove Env rm -r [env_name]/

django main app settings setup

View Details
  STATIC_URL = '/static/'
  TEST_PAYLOAD_PATH = str(BASE_DIR) + '/utils/test/'
  TEST_DATA_PATH = TEST_PAYLOAD_PATH + 'data/'
  TEST_RUNNER = 'cmtestrunner.CMTestRunner'
  TEST_APPS = ()

  LOCALE_DIR = str(BASE_DIR) + '/locale'
  TEST_SERVER = ''
  TEST_ENV = 'SIT'
  AUTH_BASE_URL = ''

Cmd into a script

View Code
import os, sys
import json


app_name = ""

def run_cmd(cmd):
    os.system(cmd)

def read_json(fileName):
    with open(fileName, 'r') as file:
        data = json.load(file)
    return data


def go_deep(body):
    
    if isinstance(body,dict):
        if 'item' in body:
            go_deep(body['item'])
        else:
            b_t = body['name']
            b_x = body['request']['method']
            b_u = "/"+"/".join(body['request']['url']['path'])
    
            temp_json = {
                "-t" : b_t,
                "-X" : b_x,
                "-u" : b_u,
                "-a" : app_name
            }
            cmruntester_cmd(temp_json)
            # print(temp_json)
    if isinstance(body,list):
        if len(body) != 0:
            for i in body:
                go_deep(i)
    

def parse_postman(fileName):
    go_deep(read_json(fileName))


def write_in_settings(project_name,index,text):

    with open(project_name+"/settings.py","r") as file:
        contents = file.readlines()

    # contents.insert(39, "    'utils',\n    'cmtestrunner',\n")
    contents.insert(index,"    '"+text+"',\n")

    with open(project_name+"/settings.py","w") as file:
        contents = "".join(contents)
        file.writelines(contents)


# create utils dir
def iwanttotest_cmd(project_name, app_name, base_url, base_env ):

    try:
        # dir_name = os.getcwd().split("/")
        # project_name = dir_name[len(dir_name)-1]

        with open(project_name+"/settings.py","a") as file:
            temp = "\nTEST_PAYLOAD_PATH = str(BASE_DIR) + '/utils/test/'\nTEST_DATA_PATH = TEST_PAYLOAD_PATH + '/data/'\nTEST_RUNNER = 'cmtestrunner.CMTestRunner'\nTEST_APPS = ()\nLOCALE_DIR = str(BASE_DIR) + '/locale'\nTEST_SERVER = ''\nTEST_ENV = '"+base_env+"'\n"
            temp = temp + app_name.upper() +"_BASE_URL = '"+base_url+"'"
            file.write(temp)

        run_cmd("env/bin/python3 manage.py iwanttotest")
    except:
        print("Failed to created")

    write_in_settings(project_name, 40, 'utils')


# create app
def create_app_cmd(app_name):
    run_cmd("env/bin/python3 manage.py startapp "+app_name)


# remove files except __init__.py
def rm_cmd(app_name):
    src_path = app_name+"/"
    dest_path = "./"
    file_name = "__init__.py"

    run_cmd("mv "+ src_path + file_name +" "+ dest_path)
    run_cmd("rm -r "+ app_name +"/*")
    run_cmd("mv "+file_name +" "+ src_path)


# gen method.py api.py and .csv
def cmruntester_cmd(data):

    parse_data = " ".join([ key +" "+ data[key] for key in data])
    # print(parse_data)
    cmd = "env/bin/python3 manage.py createtest "+parse_data
    print(data['-t'],end=" ")
    run_cmd(cmd)


def setup_lib(project_name,env_mode):

    run_cmd("django-admin startproject "+project_name)
    os.chdir(project_name)

    # by default virtual env is off, to on pass value 1 in argv
    if not env_mode:
        run_cmd("python3 -m venv env")
        run_cmd("env/bin/pip3 install cmtestrunner")
    # else:
        # run_cmd("pip install cmtestrunner")

    write_in_settings(project_name,39,'cmtestrunner')


'''
user need to things to do
1. activate virtual env if have any
2. postman json export 
'''
if __name__ == "__main__":

    postman_json_file = "../filename.json"
    project_name = "name"
    app_name = "name"
    base_url = "url"
    base_env = "SIT/UAT"

    env_mode = 0
    if len(sys.argv)>1:
      env_mode = int(sys.argv[1])

    setup_lib(project_name,env_mode)
    iwanttotest_cmd(project_name, app_name, base_url,base_env)

    create_app_cmd(app_name)
    rm_cmd(app_name)
    parse_postman(postman_json_file)

Issues

  • Put this in at the bottom of "env/bin/acitvate"
export DJANGO_SETTINGS_MODULE=mysite.settings
  • Never Forget to put app name in django settings.
  • env/lib/python3.8/site-packages/cmtestrunner/management/commands/iwanttotest.py
str(DIR) +"/..."

https://stackoverflow.com/questions/48001164/typeerror-unsupported-operand-types-for-posixpath-and-str

asgiref==3.5.2
backports.zoneinfo==0.2.1
certifi==2021.10.8
charset-normalizer==2.0.11
cmtestrunner==2.1.2
Django==3.2
djangorestframework==3.13.1
idna==3.3
Naked==0.1.31
numpy==1.23.2
pyasn1==0.4.8
pytz==2022.2.1
PyYAML==6.0
requests==2.27.1
rsa==4.8
shellescape==3.8.1
six
sqlparse==0.4.2
urllib3==1.26.8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment