test_prompt_comparision

python 11 hours, 54 minutes ago
import unittest from unittest.mock import Mock, patch import pandas as pd from datetime import datetime from your_module import PromptComparisonReport # Replace 'your_module' with the actual module name class TestPromptComparisonReport(unittest.TestCase): def setUp(self): # Create mock objects for dependencies self.mock_mongo_service = Mock() self.mock_auth = Mock() self.mock_config = { 'cloud-ai': { 'STRING_DISTANCE_URL': 'http://example.com/string_distance', 'STRING_COSINE_DISTANCE_URL': 'http://example.com/string_cosine_distance' } } # Initialize the PromptComparisonReport with mocks self.report_service = PromptComparisonReport(self.mock_config, self.mock_mongo_service, self.mock_auth) @patch('your_module.pd.DataFrame') def test_get_master_data_from_mongo(self, mock_dataframe): # Simulate MongoDB data self.mock_mongo_service.execute_query.return_value = [ {'call_id': '1', 'model_results': {'callSummary': [{'Caller Objective': 'Intent1'}]}}, {'call_id': '2', 'model_results': {'callSummary': [{'Caller Objective': 'Intent2'}]}} ] # Test the get_master_data_from_mongo method df = self.report_service.get_master_data_from_mongo() # Assertions self.mock_mongo_service.execute_query.assert_called_once_with('ai_intent_action_golden_copy') mock_dataframe.assert_called() self.assertIn('callID', df.columns) @patch('your_module.pd.DataFrame') def test_get_model_results_from_mongo(self, mock_dataframe): # Simulate data returned by MongoDB query run_time = '2024-01-01' self.mock_mongo_service.execute_query.return_value = [ {'call_id': '1', 'model_results': {'callSummary': [{'Caller Objective': 'Intent1'}]}}, {'call_id': '2', 'model_results': {'callSummary': [{'Caller Objective': 'Intent2'}]}} ] # Test the method with a single run_time df = self.report_service.get_model_results_from_mongo(run_time) # Assertions query = {'run_time': datetime.strptime(run_time, '%Y-%m-%d')} self.mock_mongo_service.execute_query.assert_called_once_with('ai_intent_action', query) self.assertIn('callID', df.columns) def test_create_dict_for_comparing(self): # Test data to pass into create_dict_for_comparing test_data = pd.DataFrame({ 'callID': [1, 2], 'model_results_from': [ [{'Caller Objective': 'Intent1'}], [{'Caller Objective': 'Intent2'}] ], 'model_results_to': [ [{'Caller Objective': 'Intent3'}], [{'Caller Objective': 'Intent4'}] ] }) result = self.report_service.create_dict_for_comparing(test_data) # Check if the result dictionary is as expected self.assertEqual(result[0]['call_id'], 1) self.assertEqual(result[1]['call_id'], 2) self.assertEqual(result[0]['google_naming'], ['INTENT1']) self.assertEqual(result[1]['google_naming'], ['INTENT2']) @patch('your_module.requests.Session') def test_calling_labelling_api_azure(self, mock_session): # Mock the session's post method to return a mock response mock_response = Mock() mock_response.content = b'{"DATA": "test_data"}' mock_session.return_value.post.return_value = mock_response # Run the method with test data response = self.report_service.calling_labelling_api_azure( 'http://example.com/test', {'data': 'test'}, 'fake_token' ) # Assertions self.assertEqual(response.content, b'{"DATA": "test_data"}') mock_session.return_value.post.assert_called_once_with( url='http://example.com/test', data='{"data": "test"}' ) def test_getting_comparison_report(self): # Mock data and dependencies self.report_service.calling_labelling_api_azure = Mock(return_value=Mock(content=b'{"DATA": [{"DISTANCE": 0.1}]}')) self.mock_auth.generate_assertion_token.return_value = 'fake_token' # Prepare test input data = [{'call_id': 1, 'google_naming': ['INTENT1'], 'azure_naming': ['INTENT2']}] # Test with "cosine" type result = self.report_service.getting_comparison_report(data, "cosine") # Assertions self.assertIn("cosine_DISTANCE", result.columns) self.assertAlmostEqual(result['cosine_DISTANCE'].iloc[0], 0.1) @patch('your_module.StreamingResponse') def test_format_data_for_report_excel(self, mock_streaming_response): # Prepare test data test_df = pd.DataFrame({ 'CALL_ID': [1, 2], 'GOOGLE_NAMING': ['Intent1', 'Intent2'], 'AZURE_NAMING': ['Intent3', 'Intent4'], 'euc_DISTANCE': [0.1, 0.2], 'cosine_DISTANCE': [0.3, 0.4] }) model_tagged_data = pd.DataFrame({ 'model_name': ['TestModel'], 'intent_action_prompt_name': ['TestPrompt'] }) # Run with excel output type self.report_service.format_data_for_report(test_df, model_tagged_data, 'excel') # Assertions mock_streaming_response.assert_called_once() self.assertIn("attachment", mock_streaming_response.call_args[1]['headers']['Content-Disposition']) def test_format_data_for_report_json(self): # Prepare test data test_df = pd.DataFrame({ 'CALL_ID': [1, 2], 'GOOGLE_NAMING': ['Intent1', 'Intent2'], 'AZURE_NAMING': ['Intent3', 'Intent4'], 'euc_DISTANCE': [0.1, 0.2], 'cosine_DISTANCE': [0.3, 0.4] }) model_tagged_data = pd.DataFrame({ 'model_name': ['TestModel'], 'intent_action_prompt_name': ['TestPrompt'] }) # Run with JSON output type response = self.report_service.format_data_for_report(test_df, model_tagged_data, 'json') # Assertions self.assertIsInstance(response, JSONResponse) self.assertIn("Status", response.body.decode('utf-8')) if __name__ == '__main__': unittest.main()
12
Posted By
Python Script to create AWS beanstalk
#!/usr/bin/python
  
import boto
python aws beanstalk
sandeep sandeep
List all files and folders using python os mo
import os

def list_files_folders(path):
python python-os
kishore_kumar
Get current environment variables in python
import os
env = os.environ

python python-os
kishore_kumar
Get os details using python os
import os
print os.uname()
# Don't use os.system('uname -a'), its j
python python-os
kishore_kumar
Get stats ( lines, words, char count ) of fil
def file_stats(path):
    f = open(path, 'r')
    lines = f.readlines()
python
kishore_kumar
Use map function in python
def get_double(num):
    return num * 2

python
kishore_kumar
Python sample codes for beginners
print "Welcome to python"
python
gaya38 gaya38
Python program for even number checking
a=input("Enter a value:")
if (a%2==0):
    print "The given number is even numb
python
gaya38 gaya38
Python program for prime number check
a=input("Enter a value:")
k=0
b=(a/2)+1
python
gaya38 gaya38
Pass command line arguments in python
import sys
x=len(sys.argv)
a=[]
python
gaya38 gaya38
Python program for the largest number in an a
a = [1,43,98,5]#Dummy data
for l in range(len(a)-1):
        if (a[l]>a[l+1]):
python
gaya38 gaya38
print list of even numbers within a range
n=100
a=[10,20,30,40,50]
b=[60,70,80,90]
python
gaya38 gaya38
generate fibonacci series in python
n=input("Enter the constraint to print n
m=input("Enter the maximum value to prin
a=0
python
gaya38 gaya38
Generate Random number within the range in py
import random
print random.uniform(10,500)
python
gaya38 gaya38
Shuffle list elements in python
import random;
z = [1,90,4,2]
z = random.shuffle(z)
python
gaya38 gaya38
use python requests to get contents of url (
import requests

req = requests.get("https://httpbin.org/
python python-requests
kishore_kumar
how to iterate or get values in python dictio
sample_dict = { "number": 1, "fruits": [

for key in sample_dict:
python
kishore_kumar
create matrix and multiply using numpy in pyt
import numpy as np

matrix = [[1,2,3], [4,5,6], [7,8,9]]
python numpy
kishore_kumar
generate random numbers matrix with numpy pyt
import numpy as np

random_arr = np.random.randint(1,50,9)
python numpy
kishore_kumar
Find min , max and mean for numpy arrays
import numpy as np

random_arr = np.random.randint(1,50,9)
python numpy
kishore_kumar