From 078d611713e9ca52c429c463fdc28dfd588fa56b Mon Sep 17 00:00:00 2001 From: yusuf jimoh Date: Mon, 3 Jun 2024 13:35:02 +0100 Subject: [PATCH] perform a test driven development to read file_name from an ascii file in python --- .idea/misc.xml | 1 + exercises-python/template/ex01_basics/main.py | 10 +++++++++- .../template/ex01_basics/test_wordcount.py | 20 +++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 exercises-python/template/ex01_basics/test_wordcount.py diff --git a/.idea/misc.xml b/.idea/misc.xml index 5652fc62..4b4a2e59 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -6,4 +6,5 @@ + \ No newline at end of file diff --git a/exercises-python/template/ex01_basics/main.py b/exercises-python/template/ex01_basics/main.py index 28ac3b0b..dc750397 100755 --- a/exercises-python/template/ex01_basics/main.py +++ b/exercises-python/template/ex01_basics/main.py @@ -1,9 +1,17 @@ #!/usr/bin/env python3 +def read_ascii_file(param): + try: + f = open(param, 'r') + return f.read() + except FileNotFoundError: + print("Oops! That was not a valid file. Try again...") def main(): - pass + read_ascii_file("file.txt") if __name__ == "__main__": main() + + diff --git a/exercises-python/template/ex01_basics/test_wordcount.py b/exercises-python/template/ex01_basics/test_wordcount.py new file mode 100644 index 00000000..24f98dd0 --- /dev/null +++ b/exercises-python/template/ex01_basics/test_wordcount.py @@ -0,0 +1,20 @@ +import unittest +from unittest.mock import mock_open, patch +from main import * + + +class WordCountTest(unittest.TestCase): + + def setUp(self): + # Create a temporary ASCII file for testing + self.filename = 'file.txt' + + @patch('builtins.open', new_callable=mock_open, read_data='This is a test data') + def test_get_file_name_from_arg(self, mock_file): + content = read_ascii_file(self.filename) + expected_content = 'This is a test data' + self.assertEqual(content, expected_content) + mock_file.assert_called_once_with(self.filename, 'r') + + +