Skip to main content

Implementing Open AI in Software Testing: Creating a Model for Test Case Review/Optimization

This article shows how QA teams and developers may create AI assistants by integrating OpenAI's cutting-edge AI technologies. In this instance, we are setting up the OpenAI package using our specific API key. This key is essential because it provides us with access to the OpenAI platform and allows us to take advantage of all its features.

Steps to Build the Model and Web App:

Pre-requisite:

Ø Go through this: https://platform.openai.com/docs/quickstart?context=python

Ø Install Python and other dependencies like streamlit, openAI, etc. on your machine using the PIP package installer if you are planning to run it on your local.

Ø Create an Open API account, and generate API key using https://platform.openai.com/api-keys (Note* You receive free $5 when signing up using your mobile phone, which is sufficient for you to play with.)

Step 1: Create a GitHub Account and Create a New Repository

1.     Go to GitHub’s website.

2.    Click on the “Sign up” button in the top-right corner. Provide valid details to sign-up.

3.    Once logged in, click on the “+” icon in the top-right corner and select “New repository.”

4.    Give your repository a name, such as “test-case-review

5.    Choose if you want your repository to be public or private.

6.    Initialize the repository with a README file.

7.     Click “Create repository.”

 

Step 2: Add Files to Your Repository

1.     In your repository, click on “Add file” and select “Create new file.”

2.    Create a file named app.py—this will be your main Python file for the Streamlit app.

3.    Write your Streamlit code into app.py.

4.    Create another file named requirements.txt. This file should list all Python libraries that your app depends on, including streamlit and openai.

5.    Commit the new files by clicking “Commit new file.”


Here is app.py:

import os

import openai

import streamlit as st

import time


# Retrieve the API key from the environment variable

OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')


# Initialize the OpenAI client with the API key

openai.api_key = OPENAI_API_KEY


# Create the Assistant

try:

    assistant = openai.beta.assistants.create(

        name="Test Automation Co-Pilot",

        instructions="You are an AI assistant specialized in software testing. Analyze the provided test scripts/use cases and offer solutions and optimizations based on them.",

        tools=[{"type": "retrieval"}],

        model="gpt-3.5-turbo"

    )

except Exception as e:

    st.error(f"An error occurred while creating the Assistant: {e}")

    raise


# Streamlit components

st.title("Test Cases Optimization Assistant")

user_query = st.text_area("Enter your test cases/use cases here to review and hit CTRL+Enter to start processing:", height=150)


if user_query:

    try:

        thread = openai.beta.threads.create()

        message = openai.beta.threads.messages.create(

            thread_id=thread.id, role="user", content=user_query

        )

        run = openai.beta.threads.runs.create(

            thread_id=thread.id,

            assistant_id=assistant.id,

            instructions="Analyze and suggest optimizations based on the test scripts.",

        )


        with st.spinner("Processing your request to review the test cases/use cases that you entered above..."):

            while True:

                run = openai.beta.threads.runs.retrieve(

                    thread_id=thread.id, run_id=run.id

                )

                if run.completed_at is not None:

                    break

                time.sleep(7)


            messages = openai.beta.threads.messages.list(thread_id=thread.id)

            st.header("Assistant's Suggestions:")

            for message in messages.data:

                if message.content and message.content[0].text.value.strip() and message.role=="assistant":

                    content = message.content[0].text.value

                else:

                    content = ""

                st.write(content)

    except Exception as e:

        st.error(f"An error occurred while processing your request: {e}")

Here is requirements.txt:

streamlit

openai

Step 3: Add Your API Key as a Secret

1.     Go to your GitHub repository’s Settings tab.

2.    Find the “Secrets” section in the left sidebar and click on “Actions.”

3.    Click on “New repository secret.”

4.    Name your secret (e.g., OPENAI_API_KEY) and paste your OpenAI API key as the value. Note* This is the key that you created from https://platform.openai.com/api-keys.

5.    Click “Add secret” to save it.

Step 4: Create a Share.streamlit.com Account

Visit https://share.streamlit.io/ and click on “Connect GitHub account” to sign up and link your Streamlit account with GitHub.


 


Step 5: Deploy Your Streamlit App

1.     Once logged into Streamlit, click on “New app.”



2.    Select the GitHub repository you created earlier.



3.    Choose the branch where your files are located.



4.    Write app.py in the "Main file path" field.



5.    In the “Advanced settings,” input your secret key (OPENAI_API_KEY) into the "Environment variables" section. P.S.: Ensure that you add the correct API Key. OpenAI API key usually starts with "sk-".



6.    Click “Deploy” to deploy your app. Streamlit will automatically install the dependencies listed in your requirements.txt file and deploy your app.

You are all set:





 

 

 

Comments

Popular posts from this blog

How to Unzip files in Selenium (Java)?

1) Using Java (Lengthy way) : Create a utility and use it:>> import java.io.BufferedOutputStream; import org.openqa.selenium.io.Zip; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream;   public class UnzipUtil {     private static final int BUFFER_SIZE = 4096;     public void unzip (String zipFilePath, String destDirectory) throws IOException {         File destDir = new File(destDirectory);         if (!destDir.exists()) {             destDir.mkdir();         }         ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));         ZipEntry entry = zipIn.getNextEntry();         // to iterates over entries in the zip folder         while (entry != null) {             String filePath = destDirectory + File.separator + entry.getName();             if (!entry.isDirectory()) {                 extractFile (zipIn, filePath);            

Encode/Decode the variable/response using Postman itself

We get a lot of use cases where we may have to implement Base64 encoding and/or decoding while building our APIs. And, if you are wondering if it is possible to encode/decode the variable/response using Postman itself or how to encode/decode the token or password in postman and save it in a variable? To Base64 encode/decode, the quickest way is to use JavaScript methods btoa, atob: atob - It turns base64-encoded ASCII data back to binary. btoa - It turns binary data to base64-encoded ASCII. Sample code : var responseBody = pm.response.json(); var parsedPwd = JSON.parse(atob(responseBody.password)); // presuming password is in the payload pm.collectionVariables.set("password", parsedPwd);

The use of Verbose attribute in testNG or POM.xml (maven-surefire-plugin)

At times, we see some weird behavior in your testNG execution and feel that the information displayed is insufficient and would like to see more details. At other times, the output on the console is too verbose and we may want to only see the errors. This is where a verbose attribute can help you- it is used to define the amount of logging to be performed on the console. The verbosity level is 0 to 10, where 10 is most detailed. Once you set it to 10, you'll see that console output will contain information regarding the tests, methods, and listeners, etc. <suite name="Suite" thread-count="5" verbose="10"> Note* You can specify -1 and this will put TestNG in debug mode. The default level is 0. Alternatively, you can set the verbose level through attribute in "maven-surefire-plugin" in pom.xml, as shown in the image. #testNG #automationTesting #verbose # #testAutomation