I m trying to run unit test inside Databricks with Nutter but return always None
notebook1
def add_nums(a, b):
return a + b
notebook2 (Where I want to make the unit test)
%pip install nutter
from runtime.nutterfixture import NutterFixture, tag
import the notebook1 in notebook 2
%run /notebook1/
I just make a tes to verify function in notebook1 is correctly added.
print(add_nums(1, 3)) # return 4 so everything fine.
class gcTestClass(NutterFixture):
def test_add(self):
assert (add_nums(1, 3) == 4)
result = gcTestClass().execute_tests()
print(result.to_string())
I get that output
Notebook: N/A - Lifecycle State: N/A, Result: N/A
Run Page URL: N/A
==================================================
No test cases were returned.
Notebook output: None
could somebody help me to figure out what I m doig wrong ?
Thanks
You need to include "asssertion_" at the beginning of the assertion test function:
class gcTestClass(NutterFixture):
def assertion_test_add(self):
assert (add_nums(1, 3) == 4)
# COMMAND ----------
result = gcTestClass().execute_tests()
print(result.to_string())
Related
New to using Pytest on APIs. From my understanding, testing creates another instance of Flask. Additionally, from the tutorials I have seen, they also suggest to create a separate DB table instance to add, fetch and remove data for test purposes. However, I simply plan to use the remote api URL as host to simply make the call.
Now, I set my conftest like this, where the flag --testenv would indicate to make the get/post call on the host listed below:
import pytest
import subprocess
def pytest_addoption(parser):
"""Add option to pass --testenv=api_server to pytest cli command"""
parser.addoption(
"--testenv", action="store", default="exodemo", help="my option: type1 or type2"
)
#pytest.fixture(scope="module")
def testenv(request):
return request.config.getoption("--testenv")
#pytest.fixture(scope="module")
def testurl(testenv):
if testenv == 'api_server':
return 'http://api_url:5000/'
else:
return 'http://locahost:5000'
And my test file is written like this:
import pytest
from app import app
from flask import request
def test_nodes(app):
t_client = app.test_client()
truth = [
{
*body*
}
]
res = t_client.get('/topology/nodes')
print (res)
assert res.status_code == 200
assert truth == json.loads(res.get_data)
I run the code using this:
python3 -m pytest --testenv api_server
The thing I expect is that the test file would simply make a call to the remote api with the creds, fetch the data regardless of how it gets pulled in the remote code, and bring it here for assertion. However, I am getting the 400 BAD REQUEST error, with the error being like this:
assert 400 == 200
E + where 400 = <WrapperTestResponse streamed [400 BAD REQUEST]>.status_code
single_test.py:97: AssertionError
--------------------- Captured stdout call ----------------------
{"timestamp": "2022-07-28 22:11:14,032", "level": "ERROR", "func": "connect_to_mysql_db", "line": 23, "message": "Error connecting to the mysql database (2003, \"Can't connect to MySQL server on 'mysql' ([Errno -3] Temporary failure in name resolution)\")"}
<WrapperTestResponse streamed [400 BAD REQUEST]>
Does this mean that the test file is still trying to lookup the database locally for fetching? I am unable to figure out on which host are they sending the test url as well, so I am kind of stuck here. Looking to get some help around here.
Thanks.
I want to create a mock ECS cluster, but it seems not to work properly. Although something is mocked (I don't get a credentials error), it seems not to "save" the cluster.
How can I create a mock cluster with moto?
MVCE
foo.py
import boto3
def print_clusters():
client = boto3.client("ecs")
print(client.list_clusters())
return client.list_clusters()["clusterArns"]
test_foo.py
import boto3
import pytest
from moto import mock_ecs
import foo
#pytest.fixture
def ecs_cluster():
with mock_ecs():
client = boto3.client("ecs", region_name="us-east-1")
response = client.create_cluster(clusterName="test_ecs_cluster")
yield client
def test_foo(ecs_cluster):
assert foo.print_clusters() == ["test_ecs_cluster"]
What happens
$ pytest test_foo.py
Test session starts (platform: linux, Python 3.8.1, pytest 5.3.5, pytest-sugar 0.9.2)
rootdir: /home/math/GitHub
plugins: black-0.3.8, mock-2.0.0, cov-2.8.1, mccabe-1.0, flake8-1.0.4, env-0.6.2, sugar-0.9.2, mypy-0.5.0
collecting ...
―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― test_foo ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
ecs_cluster = <botocore.client.ECS object at 0x7fe9b0c73580>
def test_foo(ecs_cluster):
> assert foo.print_clusters() == ["test_ecs_cluster"]
E AssertionError: assert [] == ['test_ecs_cluster']
E Right contains one more item: 'test_ecs_cluster'
E Use -v to get the full diff
test_foo.py:19: AssertionError
---------------------------------------------------------------------------------------------------------------------------------- Captured stdout call ----------------------------------------------------------------------------------------------------------------------------------
{'clusterArns': [], 'ResponseMetadata': {'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}
test_foo.py ⨯
What I expected
I expected the list of cluster ARNs to have one element (not the one in the assert statement, but an ARN). But the list is empty.
When creating a cluster, you're using a mocked ECS client.
When listing the clusters, you're creating a new ECS client outside the scope of moto.
In other words, you're creating a cluster in memory - but then ask AWS itself for a list of clusters.
You could rewrite the foo-method to use the mocked ECS client:
def print_clusters(client):
print(client.list_clusters())
return client.list_clusters()["clusterArns"]
def test_foo(ecs_cluster):
assert foo.print_clusters(ecs_cluster) == ["test_ecs_cluster"]
def test_foo(ecs_cluster):
assert foo.print_clusters(ecs_cluster) == ["test_ecs_cluster"]
#This will cause you a bug but I have fixed this bug ..so the code looks like this:
def cluster_list(ecs_cluster):
assert ecs.print_clusters(ecs_cluster) == ['arn:aws:ecs:us-east-1:123456789012:cluster/test_ecs_cluster']
#Explination
So basically you have passed the incorrect assert values..assert foo.print_clusters(ecs_cluster) --> this containes cluster arns it is in the form of an array which is ['arn:aws:ecs:us-east-1:123456789012:cluster/test_ecs_cluster'] and you are trying to access the [1] index and testing if its == "test_ecs_cluster" which is wrong so instead to that pass the full arn just to test your code ..
I am working with pytest fixtures. My test module is as follows :
import pytest
#pytest.yield_fixture
#pytest.fixture(scope="module")
def jlt() :
print("setup executed")
yield None
print("tearing up")
def test_one(jlt) :
id = 123
assert id == 123
def test_two(jlt) :
id = 456
assert id == 456
I am executing this as follows :
py.test -v --capture=no test_jlt.py
The output is :
platform linux2 -- Python 2.7.12, pytest-2.8.7, py-1.4.31, pluggy-0.3.1 -- /usr/bin/python
cachedir: ../../.cache
rootdir: /home/vandana/unix Home/pythonLearn, inifile: pytest.ini
collected 2 items
test_jlt.py::test_one setup executed
PASSEDtearing up
test_jlt.py::test_two setup executed
PASSEDtearing up
The scope="module" does not seem to be working. The fixture is getting executed for each function and not just once for the entire module.
I do not know what should be done
#pytest.yield_fixture replaces #pytest.fixture, so you should use #pytest.yield_fixture(scope="module") instead.
Note that with pytest 3.x you can simply use #pytest.fixture and use yield inside the fixture, which simplifies things a bit.
I am trying to write unit tests for a Python application and I want to write a unit test to verify that the entries in a dictionary are correct (based on the OS).
PROBLEM: I cannot mock the os that I am on. I just want to mock the os so that I can verify that the entries of a dictionary are valid. I have tried monkey patching, mocking and a patch but nothing works at the moment (which I do not doubt is due to my limited knowledge of unit-testing). The current code that I have is below. Any (detailed) help as to why this is not working or what I am doing wrong/should be doing instead will be greatly appreciated! :D
So I have:
package.subpackage.module (mymodule.py)
import sys
if platform.system() == 'Linux':
mydictionary = {"1":one, "2":two, "3":three}
elif platform.system() == 'other_os':
mydictionary = {"A":aaa, "B":bee, "c":cee}
I created a unit test here with the following code:
package.subfolder.subsubfolder.module (myunittestmodule.py)
def test_dictionary():
import sys
sys.modules['platform'] = Mock()
import platform
targetPlatform = platform
targetPlatform.system = Mock(return_value="other_os")
from package.subpackage.module import mydictionary
for entry in mydictionary:
print(entry)
# for now I use print to see if this even works
# but it only returns the dictionary for my os (linux), not anything else :(
I am a new user and I didn't find a solution for a doubt about the execution of my script, wrote in python, in Robot Framework.
The script works when I execute it on python compiler but when I execute the test case on Robot Framework, this error is showed:
===========================================================================
TestProvaPower
===========================================================================
TestPowerAngelo | FAIL |
No keyword with name 'power' found.
---------------------------------------------------------------------------
TestProvaPower | FAIL |
1 critical test, 0 passed, 1 failed
1 test total, 0 passed, 1 failed
===========================================================================
Output: c:\users\user\appdata\local\temp\RIDEjtznzw.d\output.xml
I think that this error is shown because it is necessary to pass the arguments and parameters.
Please, how can I pass these values in Robot Framework?
The test suite is:
** Settings **
Library ../../../../../Users/User/workspace/TestAngelo18.09/TestProva22.py
** Test Cases **
TestPowerAngelo
power base exponent
push ${base} ${exponent}
While my Python script is:
base = input("Insert base")
exponent =input("Insert exponent")
def power(base,exponent):
result=base**exponent
print "%d to the power of %d is %d" %(base,exponent,result)
power (base,exponent)
As part of your module definition, you are getting input from the user. When a module is being imported, you cannot use the standard input stream so an EOFError occurs. Below is a modified version of your library that is still testable via direct execution.
def power(base, exponent):
result = base**exponent
return result
if __name__ == '__main__':
base = input("Insert base")
exponent = input("Insert exponent")
result = power(base,exponent)
print "%d to the power of %d is %d" %(base, exponent, result)
Instead of using complex path in the Library import try setting python path with pybot e.g.
pybot --pythonpath /path/to/libs/where/py/file/is
And in the test suite file import it using just the name e.g. without the .py suffix.
Library TestProva22
RF treats arguments as strings by default. For literals, you can surround them with ${} or variables use Convert To Integer first. Something like this should work:
${result} = power ${2} ${4}
Should Be Equal As Integers ${result} 16