I am new to pytest
and I have been struggling to implement this part of my own library: Taking a function from a user and save that function as a variable so that that could be used and accessed throughout the testing. I am trying to pass a function that I defined in playground.py
(pretending I am a random user) to the sortoy.py
. I heard using global_variable
for this is not recommended. Is there any recommended way of doing it?
My whole Library structure looks like below:
my_library
-my_library
-__init__.py
-sortoy.py
-LICENSE
-playground.py --> This is where I am testing my code
-README.md
-setup.py
This is the code for playground.py
import my_library.sortoy
# The defined array
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
my_library.sortoy.sort_function(bubbleSort) # Taking user defined function
This is the code for sortoy.py
import pytest
small_cases = [([1], [1]), ([2, 1], [1, 2]), ([2, 2], [2, 2])]
@pytest.fixture # I was trying to use this for taking user function (It does not work however).
def sort_function(f):
return f
# The test I am trying to run
@pytest.mark.parametrize("test_case, sorted", small_cases)
def test_one_element(sort_function, test_case, sorted):
assert sort_function(test_case) == sorted
# Script version of pytest so that I could run the test_case above once I have got the user-defined function.
pytest.main(["-v"])
For the information, the library I am trying to implement is to test the user-defined function for users when they pass in the sort_function
they have created (like sorting). When my_library.sortoy.sort_function(bubblesort)
is called, this library is supposed to execute the testings(test_one_element()
in this case) automatically and show on console if it has failed or passed the tests.
Aucun commentaire:
Enregistrer un commentaire