Test a class and get output of that class to test the following class pytest

Viewed 37

The script I want to test looks like this

class cnv_classifier:
  ´´´ A class that calls another classes´´´
   def __init__(self,user_input):

   # First class
   data_loaded = ReadFile(user_input)
   data_loaded = data.load()

   
   # Second class
   cnv_df = Filter(data_loaded)
   cnv_df = cnv_df_cvf_return_cnv()


Now, I want to test the inner classes. To test the first class I have done this

pytest.fixture()
def file_to_test():
   file_to_test = "path/file_name"
   return file_to_test 

def test_data_loaded(file_to_test):
   data_loaded = ReadFile(user_input)
   data_loaded = data.load()
   assert ...

# This works

Now, to test the second class, I need the outpput of the first class. How can I do this?

I have tried introducing a return, and call the function like this

def test_data_loaded(file_to_test):
   data_loaded = ReadFile(user_input)
   data_loaded = data.load()
   assert ...
   return 

# Call the function
test_data_loaded = test_data_loaded(file_to_test)

# Test the second class using the output of the first class
def test_filter():
   cnv_df = Filter(data_loaded)
   cnv_df = cnv_df_cvf_return_cnv()
   assert ...

This does not work, when I run pytest, it says data_loaded is not found

What I am doing wrong?

1 Answers

You can do what you're trying to do in the end, and is perfectly acceptable. But the solution is a bit different.

To run a test inside another running test you should add all fixtures to the latter. In your case the code would look like this:

def test_data_loaded(file_to_test):
   data_loaded = ReadFile(user_input)
   data_loaded = data.load()
   assert ...
   return data_loaded                             # <- Here

# Test the second class using the output of the first class
def test_filter(file_to_test):
   data_loaded = test_data_loaded(file_to_test)   # <- Here
   cnv_df = Filter(data_loaded)
   cnv_df = cnv_df_cvf_return_cnv()
   assert ...
Related