In: Computer Science
how to write a unit test for a write function in python? is there a better way than running main once and checking whether the new file path exists?
How to write a unit test for a write function in python?
A method by which individual units of ASCII document. In programing, unit testing could be a method by which individual units of ASCII document, sets of one or more bug modules along with associated control data, usage procedures, and operating procedures, are tested to see if they're suitable use.
Let's take a example of factorial code --->
import sys def fact(n): if n == 0: return 1 return n * fact(n -1) def div(n): res = 10 / n return res def main(n): res = fact(n) print(res) if __name__ == '__main__': if len(sys.argv) > 1: main(int(sys.argv[1]))
Now we will write our first test case.--->
from factorial import fact class TestFactorial(unittest.TestCase): def test_fact(self): # Any method which starts with ``test_`` will considered as a test case. res = fact(5) self.assertEqual(res, 120) if __name__ == '__main__': unittest.main()
is there a better way than running main once and checking whether the new file path exists?
Yes --->
The os.path module provides some
functions for working with path names. The module is accessible for
both Python 2 & Pythn 3.
The foremost important functions are:-
os.path.exists(path) - Returns true if the trail could be a file,
directory, or a sound symlink.
os.path.isfile(path) - Returns true if the trail may be a regular
file or a symlink to a file.
os.path.isdir(path) - Returns true if the trail could be a
directory or a symlink to a directory.
Example -->
import os.path
if
os.path.isfile('filename.txt'):
print ("File exist")
else:
print ("File not exist")