Search code examples
pythonunit-testing

Unit testing functions that access files


I have two functions—one that builds the path to a set of files and another that reads the files. Below are the two functions:

def pass_file_name(self):
    self.log_files= []
    file_name = self.path+"\\access_"+self.appliacation+".log"
    if os.path.isfile(file_name):
        self.log_files.append(file_name)
    for i in xrange(7):
         file_name = self.path+"\\access_"+self.appliacation+".log"+"."+str(i+1)
         if os.path.isfile(file_name):
            self.log_files.append(file_name)
    return self.log_files


def read_log_files (self, log_file_names): 
    self.log_entrys = []
    self.log_line = []
    for i in log_file_names:
        self.f = open(i)
        for line in self.f:
            self.log_line = line.split(" ")
            #print self.log_line
            self.log_entrys.append(self.log_line)
    return self.log_entrys

What would be the best way to unit test these two functions?


Solution

  • You have two units here:

    • One that generate file paths
    • Second that reads them

    Thus there should be two unit-test-cases (i.e. classes with tests). First would test only file paths generation. Second would test reading from predefined set of files you prepared in special subdirectory of tests directory, it should test in isolation from first test case.

    In your case, you could probably have very short log files for tests. In this case for better readability and maintenance it is good idea to embed them right in test code. But in this case you'll have to improve your reading function a bit so it can take either file name or file-like object:

    from cStringIO import StringIO
    
    # ...
    def test_some_log_reading_scenario(self):
        log1 = '\n'.join([
            'log line',
            'another log line'
        ])
        log2 = '\n'.join([
            'another log another line',
            'lala blah blah'
        ])
        # ...
        result = myobj.read_log_files([StringIO(log1), StringIO(log2)])
        # assert result