Can I get the failed test case names using robot.api? - python

I am trying to get the failed test case names from a output.xml using robot api in python, I am able to get the count for failed/passed tests using the below code but could not find any methods to get test case names.
Thanks in advance.
from robot.api import ExecutionResult
result = ExecutionResult('output.xml')
result.configure(stat_config={'suite_stat_level': 2,
'tag_stat_combine': 'tagANDanother'})
stats = result.statistics
print stats.total.critical.failed
print stats.total.critical.passed
print stats.tags.combined[0].total

Probably you need ResultVisitor. Something like that should help:
from robot.api import ExecutionResult, ResultVisitor
class Visitor(ResultVisitor):
def __init__(self):
self.failed = []
def end_test(self, test):
if test.status == "FAIL":
self.failed.append(test)
visitor = Visitor()
result = ExecutionResult('output.xml')
result.visit(visitor)
print(visitor.failed)
Documentation could be found at https://robot-framework.readthedocs.io/en/v3.1.2/autodoc/robot.result.html#module-robot.result.visitor

Related

Better way to Test API?

I have function :
def is_car_exist(make, model):
url = f'https://vpic.nhtsa.dot.gov/api/vehicles/GetModelsForMake/\
{make.capitalize()}?format=json'
data = requests.get(url).json()['Results']
return any(model.capitalize() == car['Model_Name'] for car in data)
How write test to test requests method inside function ?

I have an Error with python flask cause of an API result (probably cause of my list) and my Database

I use flask, an api and SQLAlchemy with SQLite.
I begin in python and flask and i have problem with the list.
My application work, now i try a news functions.
I need to know if my json informations are in my db.
The function find_current_project_team() get information in the API.
def find_current_project_team():
headers = {"Authorization" : "bearer "+session['token_info']['access_token']}
user = requests.get("https://my.api.com/users/xxxx/", headers = headers)
user = user.json()
ids = [x['id'] for x in user]
return(ids)
I use ids = [x['id'] for x in user] (is the same that) :
ids = []
for x in user:
ids.append(x['id'])
To get ids information. Ids information are id in the api, and i need it.
I have this result :
[2766233, 2766237, 2766256]
I want to check the values ONE by One in my database.
If the values doesn't exist, i want to add it.
If one or all values exists, I want to check and return "impossible sorry, the ids already exists".
For that I write a new function:
def test():
test = find_current_project_team()
for find_team in test:
find_team_db = User.query.filter_by(
login=session['login'], project_session=test
).first()
I have absolutely no idea to how check values one by one.
If someone can help me, thanks you :)
Actually I have this error :
sqlalchemy.exc.InterfaceError: (InterfaceError) Error binding
parameter 1 - probably unsupported type. 'SELECT user.id AS user_id,
user.login AS user_login, user.project_session AS user_project_session
\nFROM user \nWHERE user.login = ? AND user.project_session = ?\n
LIMIT ? OFFSET ?' ('my_tab_login', [2766233, 2766237, 2766256], 1, 0)
It looks to me like you are passing the list directly into the database query:
def test():
test = find_current_project_team()
for find_team in test:
find_team_db = User.query.filter_by(login=session['login'], project_session=test).first()
Instead, you should pass in the ID only:
def test():
test = find_current_project_team()
for find_team in test:
find_team_db = User.query.filter_by(login=session['login'], project_session=find_team).first()
Asides that, I think you can do better with the naming conventions though:
def test():
project_teams = find_current_project_team()
for project_team in project_teams:
project_team_result = User.query.filter_by(login=session['login'], project_session=project_team).first()
All works thanks
My code :
project_teams = find_current_project_team()
for project_team in project_teams:
project_team_result = User.query.filter_by(project_session=project_team).first()
print(project_team_result)
if project_team_result is not None:
print("not none")
else:
project_team_result = User(login=session['login'], project_session=project_team)
db.session.add(project_team_result)
db.session.commit()

Mocking return value of a nested call in Python mock library

Brand new to this library
Here is the call stack of my mocked object
[call(),
call('test'),
call().instance('test'),
call().instance().database('test'),
call().instance().database().snapshot(),
call().instance().database().snapshot().__enter__(),
call().instance().database().snapshot().__enter__().execute_sql('SELECT * FROM users'),
call().instance().database().snapshot().__exit__(None, None, None),
call().instance().database().snapshot().__enter__().execute_sql().__iter__()]
Here is the code I have used
#mock.patch('testmodule.Client')
def test_read_with_query(self, mock_client):
mock = mock_client()
pipeline = TestPipeline()
records = pipeline | ReadFromSpanner(TEST_PROJECT_ID, TEST_INSTANCE_ID, self.database_id).with_query('SELECT * FROM users')
pipeline.run()
print mock_client.mock_calls
exit()
I want to mock this whole stack that eventually it gives me some fake data which I will provide as a return value.
The code being tested is
spanner_client = Client(self.project_id)
instance = spanner_client.instance(self.instance_id)
database = instance.database(self.database_id)
with database.snapshot() as snapshot:
results = snapshot.execute_sql(self.query)
So my requirements is that the results variable should contain the data I will provide.
How can I provide a return value to such a nested calls
Thanks
Create separate MagicMock instances for the instance, database and snapshot objects in the code under test. Use return_value to configure the return values of each method. Here is an example. I simplified the method under test to just be a free standing function called mut.
# test_module.py : the module under test
class Client:
pass
def mut(project_id, instance_id, database_id, query):
spanner_client = Client(project_id)
instance = spanner_client.instance(instance_id)
database = instance.database(database_id)
with database.snapshot() as snapshot:
results = snapshot.execute_sql(query)
return results
# test code (pytest)
from unittest.mock import MagicMock
from unittest import mock
from test_module import mut
#mock.patch('test_module.Client')
def test_read_with_query(mock_client_class):
mock_client = MagicMock()
mock_instance = MagicMock()
mock_database = MagicMock()
mock_snapshot = MagicMock()
expected = 'fake query results'
mock_client_class.return_value = mock_client
mock_client.instance.return_value = mock_instance
mock_instance.database.return_value = mock_database
mock_database.snapshot.return_value = mock_snapshot
mock_snapshot.execute_sql.return_value = expected
mock_snapshot.__enter__.return_value = mock_snapshot
observed = mut(29, 42, 77, 'select *')
mock_client_class.assert_called_once_with(29)
mock_client.instance.assert_called_once_with(42)
mock_instance.database.assert_called_once_with(77)
mock_database.snapshot.assert_called_once_with()
mock_snapshot.__enter__.assert_called_once_with()
mock_snapshot.execute_sql.assert_called_once_with('select *')
assert observed == expected
This test is kind of portly. Consider breaking it apart by using a fixture and a before function that sets up the mocks.
Either set the value directly to your Mock instance (those enters and exit should have not seen) with:
mock.return_value.instance.return_value.database.return_value.snapshot.return_value.execute_sql.return_value = MY_MOCKED_DATA
or patch and set return_value to target method, something like:
#mock.patch('database_engine.execute_sql', return_value=MY_MOCKED_DATA)

Get Intent Value in RASA Core/NLU

Greeting
I am working on RASA chatbot. I am handling Custom actions for a particular intent using below code. In the custom action I want to get current intent value. SO i dont know that line of code which can give me value of current intent
#this file will be used to all custom actions
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import requests
import json
from zeep import Client
from random import randint
from rasa_core.actions.action import Action
from rasa_core.events import SlotSet
class ActionWeather(Action):
RANDOMIZE = False
#staticmethod
def required_fields():
return [
EntityFormField("period", "period"),
EntityFormField("product", "product")
]
def name(self):
return 'action_weather'
def run(self,dispatcher, tracker, domain):
#Get Slot values
loc = tracker.get_slot('period')
pro = tracker.get_slot('product')
custname= tracker.get_slot('custName')
#Here I want to get Intent Values as well same like slot value in above code
# So what is code for getting intent value
#make json
data = {}
data['period'] = loc
data['product'] = pro
json_data = json.dumps(data)
jsonobj= json.loads(json_data)
#code for SOAP
client = Client('my webservice URL/testsoap?wsdl')
result = client.service.getData(json_data)
print('**********************')
print(result)
print('#######################')
jsonobj= json.loads(result)
#print(response.content)
#json_response = response.json()
#print (json_response)
result1=jsonobj[0]['result']
#result1=randint(1, 100)
#result='X'
response = """sale is {} """.format(result1)
dispatcher.utter_message(response)
#return [SlotSet('location',loc)]
return []
I want to get current and last value of intent in RASA Core in same way as we can get slots value product = tracker.get_slot('product') in python custom action code. Please help.
This works for me:
def run(self,dispatcher, tracker, domain):
intent = tracker.latest_message['intent'].get('name')
rasa-core 0.11.12
rasa-core-sdk 0.11.5
rasa-nlu 0.13.7
intent = json.dumps(tracker.latest_message.intent)
print(intent)
#particular intent name
print(json.loads(intent)['intent']['name'])
outcome
(u'{"confidence": 0.9092543377510975, "name": "greet"}')
or try this
intent = json.dumps(tracker.latest_message.__dict__)
You can use something like below,
currentIntent = tracker.latest_message.intent["name"]

Python evernote api Error

Trying to build app that connects with Evernote API, in Python/Django. For the below code i get the following error message: " 'Store' object has no attribute 'NoteFilter' " from http://dev.evernote.com/documentation/reference/NoteStore.html#Svc_NoteStore One can see, that NoteFilter is attribute of NoteStore.
def list(request):
nbname="mihkel's notebook"
client = EvernoteClient(token=token, sandbox=False)
note_store = client.get_note_store()
notebooks = note_store.listNotebooks()
for nb in notebooks:
if nbname == nb.name:
nb = nb
filter = note_store.NoteFilter()
filter.notebookGuid = nb.guid
notelist = note_store.findNotes(token,filter,0,10)
break
return render_to_response('list.html', {'nb': nb, 'notelist':notelist})
Solution:
from evernote.edam.notestore import NoteStore
....
....
def list.. :
...
Filter = NoteStore.NoteFilter()
notestore/ttypes.py has the definition for NoteFilter
Some of the examples in the API code import like this
import evernote.edam.notestore.NoteStore as NoteStore
import evernote.edam.type.ttypes as Types
Not sure if this would be an acceptable way to correct, but I added this:
import evernote.edam.notestore.ttypes as NoteStoreTypes
and created my filter like this:
filter = NoteStoreTypes.NoteFilter()

Categories