I wonder how we can clear the directories after unit test in Python. I need to do it inside the classmethod tearDownClass
instead of tearDown
because I only want to clear this up once all the tests are done, not after every single test. The reason of this is that the created files and directories will be used in the next tests. But, at the same time, I also want to pass the directory path to setUp
because I need that to instantiate my object. For example:
import unittest
import os
import pandas as pd
class Class1():
def __init__(self,in_dir,out_dir):
self.in_dir = in_dir
self.out_dir = out_dir
self.excel_path = os.path.join(self.out_dir,'Excels')
def create_dir(self):
os.makedirs(self.excel_path)
text = {'text':['ABC']}
df = pd.DataFrame(text)
df.to_csv(os.path.join(self.excel_path,'test1.csv'))
def use_csv(self):
for root,dirs,files in os.walk(self.excel_path):
df = pd.DataFrame()
for file in files:
df_append = pd.read_csv(os.path.join(root,file))
df = df.append(df_append)
return df
class TestA(unittest.TestCase):
def setUp(self):
self.in_dir = './in_dir'
self.out_dir = './out_dir'
self.C = Class1(self.in_dir, self.out_dir)
@classmethod
def setUpClass(cls):
#how to call out_dir in this classmethod?
if not os.path.exists(cls.out_dir):
os.makedirs(cls.out_dir)
@classmethod
def tearDownClass(cls):
#how to call out_dir in this classmethod?
shutil.rmtree(cls.out_dir)
def test_1(self):
self.C.create_dir()
self.assertEqual(len(os.listdir(self.C.excel_path)),1)
def test_2(self):
self.assertIsInstance(self.C.use_csv(),pd.DataFrame)
If I clear up the directories using tearDown
I will remove the generated test1.csv
after testing test_1
, hence, I'm thinking to use tearDownClass
instead.
Thanks!