Skip to content

C++ and Python Code  #17

@omarokasha1

Description

@omarokasha1

Problem Statement :

How to make automated testing through running some scripts


Technology Used :

Python and C++ as these are the Languages I can use Easily and Can support with them

In Python :

I used Python Requests and Json Technology to Communiate with the API

In C++ :

I used C++ CPR "CURL FOR HUMAN" and I used Nomral Libraries and An Important Hint to Run the Project you need to focus over the Makefile Technology


Setup Python3 Environment over Linux :

  • Installation Python3
 sudo apt install python3
  • Installation pip3 - pip3 is the Package Installer for Python to ubuntu system to can be used from any software as Import requests :
 sudo apt-get -y install python3-pip
  • Installation Requests - Requests is a library used for communicating over HTTP with the Server/API
 pip3 install requests
  • For JSON : Is Normally Installed inside Python

  • For the IDE you can use Geany

sudo apt-get install geany

Python Code :

This code to test and register a limited number of Users to the API

Thanks to @mirette3 a miswriting words has been fixed

# Adding Libraries that we will use in our Program : 

import requests 
# For Importing Library Requests
import json 
# For Importing Library Json

# ------------------------------------------------------------

# Test Connection to server


response = requests.get("http://10.5.62.214:8080/") 
# make HTTP Get Request to check if the Server Live or Not

print(response)
# print the Response of the Server which usually will be Status 200 

# ------------------------------------------------------------

# We need to start automating Register to the API 
# Through Using a While Loop we will have a Counter inside that will break the loop after reaching special Number 
# Through the Loop the Application will send to the Api the Needed Data using Requests Function and we will receive the response and validate it
# API need to send to it a Unique userName , Email , Phone 
# So we Fixed the username and Email through a variable called Keyword
# Validation over the Phone Number is the number must be 11 Number through a Fixed Variable will changed everytime based on the counter



keyword = 'omar'
# The Variable Used to create the userName and Email

Phonee =44140002000*2
# The Variable used to create the Phone Number will call it Phonee

i=0
# Initiate the Counter 

while 1:
  # Starting of the Loop
  # Must take in consideration the Spaces as Python Senstive for the Spaces 
  
  email=keyword+str(i)+"@[gmail.com](http://gmail.com/)"
  # Create Email Variable using the Keyword and the Current counter and @gmail.com for example omar0@gmail.com
  
  password="1111111111111"+str(i)
  # Create Password Variable using a fixed string which is "1111111111111" and the Current counter 

  phone=str(Phonee+i)
   # Create Phone Variable using the sum of  Phonee and Current counter 
  
  username=keyword+str(i)
   # Create username Variable using the String sum of  keyword and Current counter as String which will be omar0 
  
 
  r = requests.post('http://10.5.62.214:8080/api/register', json={"email":email,"password":password,"phone":phone,"userName":username})
  # Here Code make a POST request by sending to the API 'http://10.5.62.214:8080/api/register' a json body as mentioned above and store the response at " r "

  #print(r)
  # Print all the response
  
  print(r.json())
  # print the JSON Content

  x=r.json()
  # store the JSON Content inside new Variable 

  print(x['token'])
  # print the attribute that have the key token
  
  i=i+1
  # Increment the Counter

  if(i==1000000):
    break
  # Break the Loop if we reached that Number of Rounder or Users Registers 


------------------------------------------------------------

Setup C++Environment over Linux :

Installation gcc

 sudo apt-get install gcc

Installation g++

 sudo apt-get install g++

Installation eclipse for C++

> Visit the URL Below

https://www.eclipse.org/downloads/packages/

image

> Search for Eclipse for C++

image

> Download Linux [x86_64]

> After Downloading unzip the file and open the folder and double click on eclipse file

> Accept all Eclipse Setup for Location to be used to save projects

> From FIle > New Project > C++ Project > Cmake > Cmake Project > Give the Project name > Then hit finish

> The Reason Behind Using Cmake to can download libraries online and add them to the project meanwhile it will help you in building the project easily and can help in future to add more libraries and even export project to be executed on other devices Thanks to @KareemAhmed22 this has been added

> You will find at the left Project Explore that have 2 Main files : Your Project name .cpp and CMakeList.txt and Binaries and Build Folder

Your Code will be Inside the Your Project name .cpp
To Download Libraries Online and Use it inside your Project we will use in future CMakeList.txt
Build Folder Where the Downloaded Libraries will built with their dependences
Binaries Folder for the Executables Files

After Understanding Eclipse Let's Add our Library " cpr C++ "

First of All Visit this repo on github as this library we are going to use and have a look at readme :

https://github.com/libcpr/cpr

image

You will find out Label for Usage :

image

You will find some CMakeList.txt Scripts

You will copy them and paste at your CMakeFile.txt at your project inside Eclipse
Below is my CMakeFile.txt you can use it directly but Every Omar Word Replace it in the next code with your Project name

cmake_minimum_required (VERSION 2.6)

project (omar)

add_executable(omar omar.cpp)
include(FetchContent)
FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git
                         GIT_TAG beb9e98806bb84bcc130a2cebfbcbbc6ce62b335) # The commit hash for 1.7.2. Replace with the latest from: https://github.com/libcpr/cpr/releases
FetchContent_MakeAvailable(cpr)

target_link_libraries(omar PRIVATE cpr::cpr)

** Important **

You will face Problem to Make the CMakeFile.txt with each build to ensure that any update their will bounce direct back to your project.

To Solve This Check the Stackoverflow Issue and Try to follow it .

https://stackoverflow.com/questions/12574187/eclipse-cdt-no-rule-to-make-target-all

Screenshot from 2022-02-14 20-17-14

Screenshot from 2022-02-14 20-17-18

After this. When you are going to run the Project This will run automatic to ensure all libraries are supplied and up to date

C++ Code :

 // Libraries Used in the Code

#include <iostream>
// Standard Library for Input Output Operations
#include <cpr/cpr.h>
// Our Main Library for Communication with the API
#include <string>
//Handling the Strings in the Code
#include <thread>
// To make Threads to run Features Parallel
#include <sstream>
// we used it here to can Make stream to store the Phone Number then Transform it to String as Setpercision function works only with streams
#include <iomanip>
// to can use setprecision function to work to can get the float without decimal point
using namespace std;
// Using the Standard Namespace


// Main Function Used to register Accounts
// This Fucntion take 3 Variables :
// The first Variable : Keyword which is the keyword that will manipulate the Username and Email
// The Second Variable : is K which is used for Creating Phone Number
// The Third Variable : is the Number of Iteration needed to be done


void omar (string keyword,double k,int iteration)
{
	// the loop that will help with register all needed users

	for(int i = 0 ; i < iteration;i++)
	{
			stringstream stream;
			// This is to make a new string stream object called stream

			stream << std::fixed << setprecision(0) << i+k;
			// Here we are saving at stream tha sum of i + k but taking in consideration that the percision is 0 which means no decimel point and std::fixed is for keep the accuracy of our double or float to 6 digits after the decimel.

			string phone = stream.str();

			// Save at a new variable called phone the string saved in stream


			string body = "{\"userName\":\""+keyword+to_string(i)+"\",\"email\":\""+keyword+to_string(i)+"@gmail.com\",\"password\":\"abdeceasdasd\",\"phone\":\""+phone+"\"}";
			
			// Here we store the json generated order to can send it in variable called Body 
			
			auto r = cpr::Post(cpr::Url{"http://10.5.62.214:8080/api/register"}
			,
			cpr::Header{{"Content-Type","application/json"}}
			,
			cpr::Body{body});
			
			// Here in cpr we use it to make POST request by giving it the Url that we are going to use which is http://10.5.62.214:8080/api/register
			// By Giving to cpr too that the header is Application Json and then send in the bodd the body we created


//	cout<<r.text <<endl;
	}
}

int main(int argc, char **argv) {
	
	// To make the Program run multiple times parallel we start using Threads
	
	// Next we will initiate 8 Threads 
	
	// thread working like this 
	
	// thread name_of_tread(function_you_are_going_to_run , function Variables )
	
    thread th1(omar, "xxxx",19091222334,1000);

    thread th2(omar, "xxxxx",29094222334,1000);

    thread th3(omar, "xxxxxx",39066222334,1000);

    thread th4(omar, "xxxxxxx",49042223341,1000);

    thread th5(omar, "xxxxxxxx",50042223341,1000);

    thread th6(omar, "xxxxxxxxx",60042223341,1000);

    thread th7(omar, "xxxxxxxxxx",70042223341,1000);

    thread th8(omar, "xxxxxxxxxxx",80042223341,1000);

    
    // Here we start launching the Threads 
    th1.join();
    th2.join();
    th3.join();
    th4.join();
    th5.join();
    th6.join();
    th7.join();
    th8.join();

	// THe program Automatic will close after finishing all threads
	return 0;
}


After Adding this code to your project in your C++ File inside Eclipse you will need to start Compile and Run it :

First you will need to build your Project and then Run it and TaDaaaaa You are Live :)

Enjoy!

------------------------------------------------------------

For Future Development :

  • Build Login , Courses Features and Automate all Features
  • Standardize all the Features as the Program will run Based on an Input from JSON file (Configuration FIle) to can run each feature based on different inputs that C++ Program will read automatically and start implementing it
  • Generate Reports and Compare with Expectations to Generate Pass or Fail Reports

C++ Project.zip

Metadata

Metadata

Labels

documentationImprovements or additions to documentationenhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions