简体   繁体   中英

Not able to use the directories generated by tempfile library in python Unit testing Code

I am unit testing my Python code, I am using tempfile library to create a temp directory called temp_dir and save the generated output file in my temp_dir, then I want to compare this output with the already existing correct output file.

I have my class, in its setup method, I am creating temp_dir and I am removing it in tear down method as follows:

class PrimaryTest(unittest.TestCase):

  def setUp(self):
    self.temp_dir = tempfile.mkdtemp()

  def tearDown(self):
    shutil.rmtree(self.temp_dir)

Now, this temp directory I want to use in my test function to save the file generated by the functions in my Binary, the one I am testing..

Here is how I am using the above code:

  def CatalogCmp(self, product_name, actual_file, expected_file):
    doom.getCatalog(self.temp_dir, product_name)
    actual = json.load(open(actual_file))
    expected = json.load(open(expected_file))
    self.assertEqual(actual, expected)

  def testCatalogImage(self):
    expected_path = os.path.join(‘path/testdata/doom’, ’product1.json')
    actual_path = os.path.join(self.temp_dir, ’product1.json')
    self.CatalogCmp(‘product1’, actual_path, expected_path)

I am getting the following error:

IOError: [Errno 2] No such file or directory: '/tmp/tmpGmv_ZR/product1.json'

Following line is generating this error:

actual = json.load(open(actual_file))

I got some hints, which helped me to resolve the problem :

  1. Actually, I am creating the temp directory twice by calling self.temp_dir in the function CatalogCmp and before the call in the test function itself, during the actual_path variable creation, this creates two different directories for both the calls, although this might not be the direct cause of the given error, but it is wrong. So now I am creating the temp directory only once in my test function and saving the variable and passing the same to other places.

  2. One more thing which was wrong was that the function which I am testing actually accepts the list variable rather than just the product name. So maybe the function being tested was not even generating any output. Sorry, I think someone here would have definitely helped, but I can't put all the code here. So when I tried calling my function like this: doom.GetCatalog(selftemp_dir, [product_name]). It is working now. but I wonder why the error was not relevant to catch this error. How I would have checked if the function was even called properly or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM