diff --git a/FizzBuzz.py b/FizzBuzz.py index 00b6ebd..32a74fe 100644 --- a/FizzBuzz.py +++ b/FizzBuzz.py @@ -1,16 +1,17 @@ """ Q1. Why is the report method untestable ? [2 pts] - +Ans: dependency on external collabrators. [file operation] Q2. How will you change the api of the report method to make it more testable ? [2 pts] +Ans: def report(self, numbers, FileHandlerMock) """ class FizzBuzz(object): - def report(self, numbers): + def report(self, numbers, MyStub): report_file = open('c:/temp/fizzbuzz_report.txt', 'w') diff --git a/TestFizzBuzzMocked.py b/TestFizzBuzzMocked.py index 6f1d0d5..a4b4bfa 100644 --- a/TestFizzBuzzMocked.py +++ b/TestFizzBuzzMocked.py @@ -17,7 +17,19 @@ def tearDown(self): self.fb = None def test_report(self): - pass + #inpur numbers + numbers =[1,2,3,4] + #create mock file handler + mock_opener_interface = self.mock() + mock_file = self.mock() + #set expectations + self.expectAndReturn(mock_opener_interface.open('c:/temp/fizzbuzz_report.txt', 'w'), mock_file) mock_file.write("3 fizz \n") mock_file.close() + #replay + self.replay() + #call prod method + self.fb.report(numbers, opener=mock_opener_interface.open) + # verify + self.verify() diff --git a/TestFizzBuzzStubbed.py b/TestFizzBuzzStubbed.py index 78ee454..c716e7e 100644 --- a/TestFizzBuzzStubbed.py +++ b/TestFizzBuzzStubbed.py @@ -4,12 +4,14 @@ """ Q3. What will be printed when we execute 'python FizzBuzzStubbed.py' ? [3 pts] - - - - - - +setUpClass FizzBuzzStubbed +setup +test_report +teardown +setup +test_report +teardown +tearDownClass Q4. Implement MyStub class so that you can send it as a fake object to the @@ -17,14 +19,20 @@ """ class MyStub(object): - pass - - - - - - + def __init__(self): + self.values = [] + + def write(self, value): + self.values.append(value) + + def close(self): + self.closed = True + def open_stub(self): + def open(fpath, mode): + return self + return open + class TestFizzBuzzStubbed(unittest.TestCase): @@ -49,11 +57,21 @@ def tearDown(self): def test_report(self): print "test_report" - pass + myStub = MyStub() + fileopener = myStub.open_stub() + numbers = [1,2,3,4] + self.fb.report(numbers, fileopener) + self.assertEqual(values[0], '3 fizz \n') + self.assertEqual(values[1], '5 buzz \n') def test_report_for_empty_list(self): print "test_report" - pass + myStub = MyStub() + fileopener = myStub.open_stub() + numbers = [] + self.fb.report(numbers, fileopener) + + if __name__ == "__main__": unittest.main()