How to Use Pytest Library to Test Python Funtions/Modules/Classes/APIS
how to initialize flask while using pytest- this is only for python+flask, other can leave this step
from flask import Flask
app = Flask(__name__)
with app.app_context():
def funtio():
pass
....
if __name__ == "__main__":
app.run()
How to Install PYtest
pip intall pytest
how to run pytest:
to run pytest we have different ways, one is using terminal, other one is using pycharm env setup
now i am saying using terminal, open terminal
>pytest (its run all test_*.py files)
>pytest -v (display verbose_name)
>pytest -v -s ( -s display print statement on termianal)
>pytest <filename> -v -s (this is excute only specified file)
>pytest -k <search_term> -v -s (this will search that <search_term> on funtion/method names, if it match then move to run other wise dis-select)
>pytest <file_name> -k <search_term> -v -s
>pytest -m <marker> -v -s (this will search the mark name, Mark is defined @pytest.mark.<mark_name> before the funtion/method declaration.)>pytest -m methodtest -v -s --disable-warnings ( this will not print markers warnings on terminal)
How to Write test cases using pytest:in one.py fileclass Funtion:
def __init__(self):
self.a = 2
self.b = 3
def add_number(self, a, b):
self.a = a
self.b = b
self.c = self.a + self.b
return self.c
def mul_number(self, a, b):
self.a = a
self.b = b
self.c = self.a * self.b
return self.cin test_one.py file
@pytest.fixture(scope='module')
def call():
print("----called-----")
db = Funtion()
return db
@pytest.mark.parametrize('a,b,e',[(10,20,30),(1,2,3),(2,3,5)])
def test_add_with_dynamic(call, call_feature,a,b,e):
res = call.add_number(a,b)
res2 = call_feature.get_features()
print(res2)
assert res == e
@pytest.mark.parametrize('a,b,e',[(10,20,200),(1,2,2),(2,3,6)])
def test_mult_with_dynamic(call,a,b,e):
res = call.mul_number(a,b)
assert res == eNext open terminal then run, using above menthon run procedure..
How to register custom marks in pytest
Fix Issues:
how to fix this outside of application context error:
Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context(). See the documentation for more information.
Ans: just write the entire code inside the
with app.app_context():
def funtio():
pass
....or
def funtio():
with app.app_context():
pass
....
Comments
Post a Comment