From 2dae7248aafd66126164ff802add5ae06cae70ac Mon Sep 17 00:00:00 2001 From: BlankCheng <913501223@qq.com> Date: Sat, 18 May 2024 12:53:20 +0800 Subject: [PATCH 1/4] Patch randomness in eval --- data/raw/f_243_indraneil.py | 2 +- data/raw/f_245_indraneil.py | 4 ++++ data/raw/f_247_indraneil.py | 2 +- data/raw/f_2695_junda_james.py | 5 +++-- data/raw/f_2724_hanhu.py | 14 +++++++------- data/raw/f_289_indraneil.py | 4 ++-- data/raw/f_290_indraneil.py | 2 +- data/raw/f_294_indraneil.py | 8 ++++---- data/raw/f_321_indraneil.py | 2 +- data/raw/f_367_jenny.py | 30 +++++++++++++++++++++++------- data/raw/f_541_niklas.py | 9 ++++++--- data/raw/f_582_niklas.py | 34 +++++++++++++++++++++++++--------- data/raw/f_681_xiaoheng.py | 32 ++++++++++++++++++++++---------- 13 files changed, 100 insertions(+), 48 deletions(-) diff --git a/data/raw/f_243_indraneil.py b/data/raw/f_243_indraneil.py index 28911680..ab36146a 100644 --- a/data/raw/f_243_indraneil.py +++ b/data/raw/f_243_indraneil.py @@ -57,7 +57,7 @@ class TestCases(unittest.TestCase): def setUp(self): # Set up the test file path - self.temp_dir = tempfile.gettempdir() + self.temp_dir = tempfile.mkdtemp() self.test_file_path = f"{self.temp_dir}/test_log.json" def tearDown(self): diff --git a/data/raw/f_245_indraneil.py b/data/raw/f_245_indraneil.py index dba44c36..f302734b 100644 --- a/data/raw/f_245_indraneil.py +++ b/data/raw/f_245_indraneil.py @@ -61,6 +61,7 @@ def f_1238(obj_list, attr, num_bins=30, seed=0): class TestCases(unittest.TestCase): def test_case_1(self): # Input 1: Simple list of objects with integer values from 0 to 9 + random.seed(1) obj_list = [Object(value=i) for i in range(10)] ax = f_1238(obj_list, 'value') @@ -73,6 +74,7 @@ def test_case_1(self): def test_case_2(self): # Input 2: List of objects with random Gaussian values + random.seed(2) obj_list = [Object() for _ in range(100)] ax = f_1238(obj_list, 'value', seed=77) @@ -87,6 +89,7 @@ def test_case_2(self): def test_case_3(self): # Input 3: List of objects with fixed value + random.seed(3) obj_list = [Object(value=5) for _ in range(50)] ax = f_1238(obj_list, 'value', seed=4) @@ -116,6 +119,7 @@ def test_case_4(self): def test_case_5(self): # Input 5: Large list of objects + random.seed(5) obj_list = [Object(value=random.gauss(0, 5)) for _ in range(1000)] ax = f_1238(obj_list, 'value') diff --git a/data/raw/f_247_indraneil.py b/data/raw/f_247_indraneil.py index 843dedb4..2437a209 100644 --- a/data/raw/f_247_indraneil.py +++ b/data/raw/f_247_indraneil.py @@ -28,7 +28,7 @@ def f_247(data, save_plot=False, plot_path=None): Example: >>> import tempfile - >>> temp_dir = tempfile.gettempdir() + >>> temp_dir = tempfile.mkdtemp() >>> f_247([('A', 1, 1, 1), ('B', 2, 2, 2)], save_plot=True, plot_path=f"{temp_dir}/temp_plot.png")[0] array([[ 8.66025404e-01, 4.09680598e-17], [-8.66025404e-01, 4.09680598e-17]]) diff --git a/data/raw/f_2695_junda_james.py b/data/raw/f_2695_junda_james.py index 02c4a229..4839778d 100644 --- a/data/raw/f_2695_junda_james.py +++ b/data/raw/f_2695_junda_james.py @@ -66,13 +66,14 @@ class TestCases(unittest.TestCase): def setUp(self): # Create a dummy image for testing np.random.seed(42) - self.dummy_img_path = os.path.join(tempfile.gettempdir(), 'test_image.jpg') + self.dummy_img_path = os.path.join(tempfile.mkdtemp(), 'test_image.jpg') dummy_img = np.random.randint(0, 255, (20, 20, 3), dtype=np.uint8) cv2.imwrite(self.dummy_img_path, dummy_img) def tearDown(self): # Cleanup the dummy image - os.remove(self.dummy_img_path) + if os.path.exists(self.dummy_img_path): + os.remove(self.dummy_img_path) def test_valid_input(self): def dummy_onpick(event): diff --git a/data/raw/f_2724_hanhu.py b/data/raw/f_2724_hanhu.py index 16726fbe..7dd49836 100644 --- a/data/raw/f_2724_hanhu.py +++ b/data/raw/f_2724_hanhu.py @@ -5,7 +5,7 @@ def f_2726(X, y, n_splits, batch_size, epochs): """ Trains a simple neural network on provided data using k-fold cross-validation. - The network has one hidden layer with 50 neurons and ReLU activation, and + The network has one hidden layer with 20 neurons and ReLU activation, and an output layer with sigmoid activation for binary classification. Parameters: @@ -13,7 +13,7 @@ def f_2726(X, y, n_splits, batch_size, epochs): y (numpy.array): The target data. n_splits (int): The number of splits for k-fold cross-validation. Default is 5. batch_size (int): The size of the batch used during training. Default is 32. - epochs (int): The number of epochs for training the model. Default is 10. + epochs (int): The number of epochs for training the model. Default is 1. Returns: list: A list containing the training history of the model for each fold. Each history @@ -47,7 +47,7 @@ def f_2726(X, y, n_splits, batch_size, epochs): y_train, y_test = y[train_index], y[test_index] model = tf.keras.models.Sequential([ - tf.keras.layers.Dense(50, activation='relu'), + tf.keras.layers.Dense(20, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid') ]) @@ -70,7 +70,7 @@ def setUp(self): self.y = np.random.randint(0, 2, 100) self.n_splits = 5 self.batch_size = 32 - self.epochs = 10 + self.epochs = 1 def test_return_type(self): """Test that the function returns a list.""" @@ -101,9 +101,9 @@ def test_effect_of_different_batch_sizes(self): def test_effect_of_different_epochs(self): """Test function behavior with different epochs.""" - for epochs in [5, 20]: - result = f_2726(self.X, self.y, self.n_splits, self.batch_size, epochs) - self.assertEqual(len(result), self.n_splits) # Validating function execution + epochs=5 + result = f_2726(self.X, self.y, self.n_splits, self.batch_size, epochs) + self.assertEqual(len(result), self.n_splits) # Validating function execution def run_tests(): diff --git a/data/raw/f_289_indraneil.py b/data/raw/f_289_indraneil.py index 573a6531..42c50005 100644 --- a/data/raw/f_289_indraneil.py +++ b/data/raw/f_289_indraneil.py @@ -23,7 +23,7 @@ def f_289(file_path, regex_pattern=r'\(.+?\)|\w+|[\W_]+'): Example: >>> import tempfile - >>> temp_dir = tempfile.gettempdir() + >>> temp_dir = tempfile.mkdtemp() >>> file_path = os.path.join(temp_dir, 'data.csv') >>> with open(file_path, 'w', newline='') as file: ... writer = csv.writer(file) @@ -52,7 +52,7 @@ def f_289(file_path, regex_pattern=r'\(.+?\)|\w+|[\W_]+'): class TestCases(unittest.TestCase): - base_tmp_dir = tempfile.gettempdir() + base_tmp_dir = tempfile.mkdtemp() test_data_dir = f"{base_tmp_dir}/test" def setUp(self): diff --git a/data/raw/f_290_indraneil.py b/data/raw/f_290_indraneil.py index 2930f0aa..e4c91b4f 100644 --- a/data/raw/f_290_indraneil.py +++ b/data/raw/f_290_indraneil.py @@ -22,7 +22,7 @@ def f_290(file_path: str, regex_pattern=r'\(.+?\)|\w') -> dict: Example: >>> import tempfile - >>> temp_dir = tempfile.gettempdir() + >>> temp_dir = tempfile.mkdtemp() >>> file_path = os.path.join(temp_dir, 'sample_data.json') >>> with open(file_path, 'w') as file: ... json.dump({'content': 'This is a (sample) text with some (matches) and characters.'}, file) diff --git a/data/raw/f_294_indraneil.py b/data/raw/f_294_indraneil.py index 8863274b..3486e76e 100644 --- a/data/raw/f_294_indraneil.py +++ b/data/raw/f_294_indraneil.py @@ -54,7 +54,7 @@ class TestCases(unittest.TestCase): def setUp(self): self.extensions = ['*.txt', '*.md', '*.csv'] - self.base_tmp_dir = tempfile.gettempdir() + self.base_tmp_dir = tempfile.mkdtemp() self.test_directory = f"{self.base_tmp_dir}/test/" os.makedirs(self.test_directory, exist_ok=True) @@ -70,9 +70,9 @@ def setUp(self): # Write the sample data to files for filename, content in sample_files_data.items(): with ( - open(os.path.join(self.test_directory, filename), 'w') - if os.path.exists(os.path.join(self.test_directory, filename)) - else open(os.path.join(self.test_directory, filename), 'x') + open(os.path.join(self.test_directory, filename), 'w') + if os.path.exists(os.path.join(self.test_directory, filename)) + else open(os.path.join(self.test_directory, filename), 'x') ) as file: file.write(content) return super().setUp() diff --git a/data/raw/f_321_indraneil.py b/data/raw/f_321_indraneil.py index 82209d0b..ec79d78d 100644 --- a/data/raw/f_321_indraneil.py +++ b/data/raw/f_321_indraneil.py @@ -48,7 +48,7 @@ def f_321(file_path): class TestCases(unittest.TestCase): def setUp(self): # Preparing sample JSON data for testing - self.base_tmp_dir = tempfile.gettempdir() + self.base_tmp_dir = tempfile.mkdtemp() self.test_data_folder = f"{self.base_tmp_dir}/test" os.makedirs(self.test_data_folder, exist_ok=True) diff --git a/data/raw/f_367_jenny.py b/data/raw/f_367_jenny.py index a4079cd0..e22f1e8b 100644 --- a/data/raw/f_367_jenny.py +++ b/data/raw/f_367_jenny.py @@ -6,7 +6,7 @@ def f_367(file_path="data.csv", columns=["A", "B", "C"]): """ Read a CSV file into a Pandas DataFrame, convert numeric values into floats,and draw a line chart of data in the specified columns. In addition, compute the cube-root of the data. - + Parameters: - file_path (str): Path to the CSV file. Default is 'data.csv'. - columns (list of str): List of column names from the data to plot. @@ -17,7 +17,7 @@ def f_367(file_path="data.csv", columns=["A", "B", "C"]): - DataFrame: A pandas DataFrame of the data in the CSV file. - Axes: A matplotlib Axes object showing the plotted data. - Series: A pandas Series containing the cube-root of the data. - + Requirements: - pandas - numpy @@ -31,7 +31,7 @@ def f_367(file_path="data.csv", columns=["A", "B", "C"]): >>> ax >>> croot - 0 1.0 + 0 1.0 """ df = pd.read_csv(file_path, dtype=float) ax = df[columns].plot() @@ -46,6 +46,11 @@ def f_367(file_path="data.csv", columns=["A", "B", "C"]): import os +def round_dict(d, digits): + return {k: {i: round(v, digits) for i, v in subdict.items()} for k, subdict in + d.items()} + + class TestCases(unittest.TestCase): def setUp(self): self.test_dir = tempfile.TemporaryDirectory() @@ -87,8 +92,13 @@ def test_case_1(self): self.assertTrue((df["A"].tolist() == [1, 2, 3])) self.assertTrue((df["B"].tolist() == [4, 5, 6])) self.assertTrue((df["C"].tolist() == [7, 8, 9])) - self.assertEqual(croot.to_dict(), {'A': {0: 1.0, 1: 1.2599210498948734, 2: 1.4422495703074083}, 'B': {0: 1.5874010519681996, 1: 1.7099759466766968, 2: 1.8171205928321394}, 'C': {0: 1.9129311827723894, 1: 2.0, 2: 2.080083823051904}}) - + rounded_croot = round_dict(croot.to_dict(), 6) + self.assertEqual(rounded_croot, + {'A': {0: 1.0, 1: 1.259921, 2: 1.44225}, + 'B': {0: 1.587401, 1: 1.709976, + 2: 1.817121}, + 'C': {0: 1.912931, 1: 2.0, 2: 2.080084}}) + def test_case_2(self): file_path = self.temp_files["int"] with self.assertRaises(KeyError): @@ -104,8 +114,14 @@ def test_case_3(self): self.assertTrue(df["IntColumn"].equals(pd.Series([1.0, 2.0, 3.0]))) self.assertTrue(df["FloatColumn"].equals(pd.Series([1.1, 2.2, 3.3]))) self.assertTrue(df["StringColumn"].equals(pd.Series([4.0, 5.0, 6.0]))) - self.assertEqual(croot.to_dict(), {'IntColumn': {0: 1.0, 1: 1.2599210498948734, 2: 1.4422495703074083}, 'FloatColumn': {0: 1.0322801154563672, 1: 1.300591446851387, 2: 1.4888055529538275}, 'StringColumn': {0: 1.5874010519681996, 1: 1.7099759466766968, 2: 1.8171205928321394}}) - + rounded_croot = round_dict(croot.to_dict(), 6) + self.assertEqual(rounded_croot, { + 'IntColumn': {0: 1.0, 1: 1.259921, 2: 1.44225}, + 'FloatColumn': {0: 1.03228, 1: 1.300591, + 2: 1.488806}, + 'StringColumn': {0: 1.587401, 1: 1.709976, + 2: 1.817121}}) + def test_case_4(self): file_path = self.temp_files["varied_invalid"] with self.assertRaises(Exception): diff --git a/data/raw/f_541_niklas.py b/data/raw/f_541_niklas.py index 667d1144..db64f322 100644 --- a/data/raw/f_541_niklas.py +++ b/data/raw/f_541_niklas.py @@ -53,6 +53,9 @@ def run_tests(): runner.run(suite) class TestCases(unittest.TestCase): + def setUp(self) -> None: + np.random.seed(42) + def test_case_1(self): df = pd.DataFrame(np.random.randn(10, 3), columns=['a', 'b', 'c']) df = f_541(df, ['a', 'b']) @@ -60,9 +63,9 @@ def test_case_1(self): self.assertTrue('a' in df.columns) self.assertTrue('b' in df.columns) self.assertTrue('c' in df.columns) - self.assertTrue(np.all(df['a'] >= -3) and np.all(df['a'] <= 3)) - self.assertTrue(np.all(df['b'] >= -3) and np.all(df['b'] <= 3)) - self.assertTrue(np.all(df['c'] >= -3) and np.all(df['c'] <= 3)) + self.assertTrue(np.all(df['a'] >= -5) and np.all(df['a'] <= 5)) + self.assertTrue(np.all(df['b'] >= -5) and np.all(df['b'] <= 5)) + self.assertTrue(np.all(df['c'] >= -5) and np.all(df['c'] <= 5)) def test_case_2(self): df = pd.DataFrame({'a': [0, 0, 0], 'b': [0, 0, 0], 'c': [0, 0, 0]}) diff --git a/data/raw/f_582_niklas.py b/data/raw/f_582_niklas.py index 60029a2b..0cece271 100644 --- a/data/raw/f_582_niklas.py +++ b/data/raw/f_582_niklas.py @@ -1,13 +1,16 @@ import pandas as pd from sklearn.cluster import KMeans -def f_582(x_list, y_list): + +def f_582(x_list, y_list, n_clusters=2, random_state=0): """ Perform K-Means clustering on the given data by first turning it into a DataFrame with two columns "x" and "y" and then return the labels and centroids. Parameters: - x_list (list): List of data corresponding to 'x' - y_list (list): List of data corresponding to 'y' + - n_clusters (int): Number of clusters to form, default to 2 + - random_state (int): Initial random state of k-means, default to 0 Returns: tuple: The labels and centroids as numpy arrays. @@ -20,23 +23,31 @@ def f_582(x_list, y_list): Example: >>> df = pd.DataFrame({'x': [1, 2, 3, 4, 5, 6], 'y': [2, 3, 4, 5, 6, 7]}) - >>> labels, centroids = f_582([1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7]) + >>> labels, centroids = f_582([1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7], 2, 0) """ df = pd.DataFrame({'x': x_list, 'y': y_list}) - kmeans = KMeans(n_clusters=2, random_state=0).fit(df) + kmeans = KMeans(n_clusters=n_clusters, random_state=random_state).fit(df) return kmeans.labels_, kmeans.cluster_centers_ + import unittest + def run_tests(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestCases)) runner = unittest.TextTestRunner() runner.run(suite) + class TestCases(unittest.TestCase): + def setUp(self) -> None: + self.random_state = 0 + self.n_clusters = 2 + def test_case_1(self): - labels, centroids = f_582([1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7]) + labels, centroids = f_582([1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7], + self.n_clusters, self.random_state) self.assertEqual(labels[0], 0) self.assertEqual(labels[1], 0) self.assertEqual(labels[2], 0) @@ -49,7 +60,8 @@ def test_case_1(self): self.assertEqual(centroids[1][1], 6.) def test_case_2(self): - labels, centroids = f_582([1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2]) + labels, centroids = f_582([1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], + self.n_clusters, self.random_state) self.assertEqual(labels[0], 0) self.assertEqual(labels[1], 0) self.assertEqual(labels[2], 0) @@ -60,7 +72,8 @@ def test_case_2(self): self.assertEqual(centroids[0][1], 2.) def test_case_3(self): - labels, centroids = f_582([1, 2, 3, 4, 5, 6], [2, 2, 2, 2, 2, 2]) + labels, centroids = f_582([1, 2, 3, 4, 5, 6], [2, 2, 2, 2, 2, 2], + self.n_clusters, self.random_state) self.assertEqual(labels[0], 0) self.assertEqual(labels[1], 0) self.assertEqual(labels[2], 0) @@ -73,12 +86,14 @@ def test_case_3(self): self.assertEqual(centroids[1][1], 2.) def test_case_4(self): - labels, centroids = f_582([0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]) + labels, centroids = f_582([0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], + self.n_clusters, self.random_state) self.assertEqual(labels[0], 0) self.assertEqual(labels[1], 0) def test_case_5(self): - labels, centroids = f_582([1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6]) + labels, centroids = f_582([1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], + self.n_clusters, self.random_state) self.assertEqual(labels[0], 0) self.assertEqual(labels[1], 0) self.assertEqual(labels[2], 0) @@ -90,6 +105,7 @@ def test_case_5(self): self.assertEqual(centroids[1][0], 5.) self.assertEqual(centroids[1][1], 5.) + run_tests() if __name__ == "__main__": - run_tests() \ No newline at end of file + run_tests() diff --git a/data/raw/f_681_xiaoheng.py b/data/raw/f_681_xiaoheng.py index 63c4d544..6ce61012 100644 --- a/data/raw/f_681_xiaoheng.py +++ b/data/raw/f_681_xiaoheng.py @@ -5,6 +5,7 @@ HAND_RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] SUITS = ['H', 'D', 'C', 'S'] + def f_681(): """ Generate a random poker hand consisting of five cards, and count the frequency of each card rank. @@ -32,7 +33,6 @@ def f_681(): Counter({'Q': 2, '2': 1, '5': 1, '4': 1}) """ - random.seed(42) hand = [] for _ in range(5): rank = random.choice(HAND_RANKS) @@ -44,47 +44,59 @@ def f_681(): return hand, rank_counts + import unittest from collections import Counter HAND_RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] SUITS = ['H', 'D', 'C', 'S'] + class TestCases(unittest.TestCase): + def setUp(self) -> None: + random.seed(42) + def test_poker_hand_length(self): """Test if the poker hand has 5 cards.""" hand, rank_counts = f_681() self.assertEqual(len(hand), 5, "The poker hand should contain 5 cards.") - + def test_card_format(self): """Test if each card in the hand is formatted correctly.""" hand, rank_counts = f_681() for card in hand: - self.assertIn(len(card), [2, 3], "Each card should be a string of length 2 or 3.") - self.assertIn(card[:-1], HAND_RANKS, "The rank of each card should be valid.") + self.assertIn(len(card), [2, 3], + "Each card should be a string of length 2 or 3.") + self.assertIn(card[:-1], HAND_RANKS, + "The rank of each card should be valid.") self.assertIn(card[-1], SUITS, "The suit of each card should be valid.") - + def test_rank_counts_type(self): """Test if rank_counts is of type Counter.""" hand, rank_counts = f_681() - self.assertIsInstance(rank_counts, Counter, "rank_counts should be a Counter dictionary.") - + self.assertIsInstance(rank_counts, Counter, + "rank_counts should be a Counter dictionary.") + def test_rank_counts_keys(self): """Test if the keys of rank_counts are valid ranks.""" hand, rank_counts = f_681() for rank in rank_counts.keys(): self.assertIn(rank, HAND_RANKS, "The ranks in rank_counts should be valid.") - + def test_rank_counts_values(self): """Test if the values of rank_counts are integers.""" hand, rank_counts = f_681() for count in rank_counts.values(): - self.assertIsInstance(count, int, "The counts in rank_counts should be integers.") + self.assertIsInstance(count, int, + "The counts in rank_counts should be integers.") + def run_tests(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestCases)) runner = unittest.TextTestRunner() runner.run(suite) + + if __name__ == "__main__": - run_tests() \ No newline at end of file + run_tests() From 7a22a3c97f2118b269e125ee468083cb5affef39 Mon Sep 17 00:00:00 2001 From: BlankCheng <913501223@qq.com> Date: Sat, 18 May 2024 13:32:36 +0800 Subject: [PATCH 2/4] Update --- data/raw/f_889_chien.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/data/raw/f_889_chien.py b/data/raw/f_889_chien.py index 948ffe6b..4b3cef8f 100644 --- a/data/raw/f_889_chien.py +++ b/data/raw/f_889_chien.py @@ -124,7 +124,8 @@ def test_current_date(self): Test the function with the current date and time. """ current_date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - self.assertEqual(f_889(current_date_str), 0) + self.assertTrue(0 <= f_889(current_date_str) <= 2) + def run_tests(): From 1403837914e6dfe7d34b0042cedcc80d48592e82 Mon Sep 17 00:00:00 2001 From: BlankCheng <913501223@qq.com> Date: Sat, 18 May 2024 14:04:23 +0800 Subject: [PATCH 3/4] Remove super() --- data/raw/f_245_indraneil.py | 2 +- data/raw/f_271_indraneil.py | 5 ++--- data/raw/f_288_indraneil.py | 9 ++++---- data/raw/f_294_indraneil.py | 2 -- data/raw/f_298_indraneil.py | 4 +--- data/raw/f_300_indraneil.py | 9 ++++---- data/raw/f_304_indraneil.py | 1 - data/raw/f_306_indraneil.py | 5 ++--- data/raw/f_307_indraneil.py | 5 ++--- data/raw/f_308_indraneil.py | 6 ++--- data/raw/f_309_indraneil.py | 45 ++++++++++++++++++++----------------- data/raw/f_312_indraneil.py | 1 - data/raw/f_316_indraneil.py | 5 ++--- data/raw/f_321_indraneil.py | 5 ++--- data/raw/f_323_indraneil.py | 5 ++--- 15 files changed, 49 insertions(+), 60 deletions(-) diff --git a/data/raw/f_245_indraneil.py b/data/raw/f_245_indraneil.py index f302734b..e272529f 100644 --- a/data/raw/f_245_indraneil.py +++ b/data/raw/f_245_indraneil.py @@ -85,7 +85,7 @@ def test_case_2(self): self.assertEqual(ax.get_ylabel(), 'Count', "Y-axis label is incorrect.") self.assertEqual(sum([p.get_height() for p in ax.patches]), len(obj_list), "Histogram data points do not match input list size.") # Check axis data - self.assertAlmostEqual(ax.get_xlim()[0], -2.57, delta=0.1, msg="X-axis lower limit is incorrect.") + self.assertAlmostEqual(ax.get_xlim()[0], -3.933336166652307, delta=0.1, msg="X-axis lower limit is incorrect.") def test_case_3(self): # Input 3: List of objects with fixed value diff --git a/data/raw/f_271_indraneil.py b/data/raw/f_271_indraneil.py index a37f3def..a678288b 100644 --- a/data/raw/f_271_indraneil.py +++ b/data/raw/f_271_indraneil.py @@ -76,11 +76,10 @@ def setup_test_directory(): class TestCases(unittest.TestCase): def setUp(self): setup_test_directory() - super().setUp() def tearDown(self): - shutil.rmtree(TEST_DIR_PATH) - super().tearDown() + if os.path.exists(TEST_DIR_PATH): + shutil.rmtree(TEST_DIR_PATH) def test_case_1(self): # Test with 5 JSON files containing various keys diff --git a/data/raw/f_288_indraneil.py b/data/raw/f_288_indraneil.py index a71ddae9..57858c26 100644 --- a/data/raw/f_288_indraneil.py +++ b/data/raw/f_288_indraneil.py @@ -52,12 +52,11 @@ def setUp(self) -> None: self.temp_dir = f"{self.base_tmp_dir}/test" if not os.path.exists(self.temp_dir): os.mkdir(self.temp_dir) - return super().setUp() - + def tearDown(self) -> None: - shutil.rmtree(self.base_tmp_dir) - return super().tearDown() - + if os.path.exists(self.base_tmp_dir): + shutil.rmtree(self.base_tmp_dir) + def test_case_1(self): # Test with the first sample directory input_text = { diff --git a/data/raw/f_294_indraneil.py b/data/raw/f_294_indraneil.py index 3486e76e..c63ed15d 100644 --- a/data/raw/f_294_indraneil.py +++ b/data/raw/f_294_indraneil.py @@ -75,12 +75,10 @@ def setUp(self): else open(os.path.join(self.test_directory, filename), 'x') ) as file: file.write(content) - return super().setUp() def tearDown(self): if os.path.exists(self.test_directory): shutil.rmtree(self.test_directory) - return super().tearDown() def test_case_1(self): matched_files = f_294('.*hello.*', self.test_directory, self.extensions) diff --git a/data/raw/f_298_indraneil.py b/data/raw/f_298_indraneil.py index e8c10c17..16df19c6 100644 --- a/data/raw/f_298_indraneil.py +++ b/data/raw/f_298_indraneil.py @@ -102,12 +102,10 @@ def setUp(self): else open(path, "x") ) as file: file.write(content) - super().setUp() def tearDown(self): shutil.rmtree(f"{self.base_dir}") - super().tearDown() - + def test_case_1(self): # Testing script1.py that should exit with code 0 return_code = f_298(self.script_paths[0]) diff --git a/data/raw/f_300_indraneil.py b/data/raw/f_300_indraneil.py index f6d4e908..bc3bbac8 100644 --- a/data/raw/f_300_indraneil.py +++ b/data/raw/f_300_indraneil.py @@ -100,13 +100,12 @@ def setUp(self): file.write(content) file_paths.append(file_path) - return super().setUp() - + def tearDown(self): # Reset the test folders after each test - shutil.rmtree(self.base_tmp_dir, ignore_errors=True) - return super().tearDown() - + if os.path.exists(self.base_tmp_dir): + shutil.rmtree(self.base_tmp_dir, ignore_errors=True) + def test_case_1(self): """Test basic functionality.""" # Create some sample files in the source folder diff --git a/data/raw/f_304_indraneil.py b/data/raw/f_304_indraneil.py index 070baa1a..c35e5684 100644 --- a/data/raw/f_304_indraneil.py +++ b/data/raw/f_304_indraneil.py @@ -54,7 +54,6 @@ class TestCases(unittest.TestCase): def tearDown(self) -> None: if os.path.exists(self.file_name): os.remove(self.file_name) - return super().tearDown() def test_case_1(self): # Test with n = 3 diff --git a/data/raw/f_306_indraneil.py b/data/raw/f_306_indraneil.py index 51395e0f..90dbac70 100644 --- a/data/raw/f_306_indraneil.py +++ b/data/raw/f_306_indraneil.py @@ -86,11 +86,10 @@ def setUp(self): for dir_name in self.dest_dirs.keys(): os.makedirs(dir_name, exist_ok=True) - return super().setUp() def tearDown(self): - shutil.rmtree(self.base_test_dir) - return super().tearDown() + if os.path.exists(self.base_test_dir): + shutil.rmtree(self.base_test_dir) def test_case_1(self): moved_file = f_306( diff --git a/data/raw/f_307_indraneil.py b/data/raw/f_307_indraneil.py index 6643c608..e33efa6e 100644 --- a/data/raw/f_307_indraneil.py +++ b/data/raw/f_307_indraneil.py @@ -95,11 +95,10 @@ def setUp(self): with open(os.path.join(self.test_directory, "file2.json"), "w") as file: json.dump(self.json_data2, file) - super(TestCases, self).setUp() def tearDown(self): - shutil.rmtree(self.test_directory) - super(TestCases, self).tearDown() + if os.path.exists(self.test_directory): + shutil.rmtree(self.test_directory) def test_case_1(self): # Test with the sample directory created diff --git a/data/raw/f_308_indraneil.py b/data/raw/f_308_indraneil.py index 5bd0ef9e..f1e64a1a 100644 --- a/data/raw/f_308_indraneil.py +++ b/data/raw/f_308_indraneil.py @@ -71,11 +71,9 @@ def setUp(self): doc.add_paragraph(paragraph) doc.save(self.test_directory + file_name) - super(TestCases, self).setUp() - def tearDown(self): - shutil.rmtree(self.test_directory) - super(TestCases, self).tearDown() + if os.path.exists(self.test_directory): + shutil.rmtree(self.test_directory) def read_docx_content(self, file_path): doc = Document(file_path) diff --git a/data/raw/f_309_indraneil.py b/data/raw/f_309_indraneil.py index 79eec7c9..5739b201 100644 --- a/data/raw/f_309_indraneil.py +++ b/data/raw/f_309_indraneil.py @@ -40,7 +40,8 @@ def f_309(directory_path='./xlsx_files/'): for row in workbook[sheet].iter_rows(): for cell in row: if isinstance(cell.value, str): - cell.value = re.sub(r'(?<=(^|[^\\])(\\\\)*)"', r'\"', cell.value) + cell.value = re.sub(r'(?<=(^|[^\\])(\\\\)*)"', r'\"', + cell.value) workbook.save(xlsx_file) processed_files += 1 @@ -104,54 +105,58 @@ def setUp(self): sheet = workbook.create_sheet(title=sheet_name) for row in rows: sheet.append(row) - workbook.save(filename=os.path.join(self.test_directory, file_info["filename"])) - - super(TestCases, self).setUp() + workbook.save( + filename=os.path.join(self.test_directory, file_info["filename"])) def tearDown(self): # Remove the test directory - shutil.rmtree(self.test_directory) - super(TestCases, self).tearDown() - + if os.path.exists(self.test_directory): + shutil.rmtree(self.test_directory) def test_case_1(self): # Process the mock Excel files processed_files_count = f_309(directory_path=self.test_directory) - + # Check the number of processed files self.assertEqual(processed_files_count, 3) - + # Check the content of file1.xlsx - workbook = load_workbook(filename=os.path.join(self.test_directory, "file1.xlsx")) + workbook = load_workbook( + filename=os.path.join(self.test_directory, "file1.xlsx")) sheet = workbook.active - self.assertEqual(sheet.cell(row=1, column=3).value, 'This is a \\"test\\" string.') + self.assertEqual(sheet.cell(row=1, column=3).value, + 'This is a \\"test\\" string.') self.assertEqual(sheet.cell(row=2, column=2).value, 'Row with \\"quotes\\"') self.assertEqual(sheet.cell(row=2, column=3).value, 'And \\"more\\" quotes.') - + def test_case_2(self): # Check the content of file2.xlsx - workbook = load_workbook(filename=os.path.join(self.test_directory, "file2.xlsx")) + workbook = load_workbook( + filename=os.path.join(self.test_directory, "file2.xlsx")) sheet1 = workbook["Sheet1"] self.assertEqual(sheet1.cell(row=1, column=1).value, 'Just a') - + sheet2 = workbook["Sheet2"] - self.assertEqual(sheet2.cell(row=1, column=2).value, "Another \"quoted\" string.") - + self.assertEqual(sheet2.cell(row=1, column=2).value, + "Another \"quoted\" string.") + def test_case_3(self): # Check the content of file3.xlsx - workbook = load_workbook(filename=os.path.join(self.test_directory, "file3.xlsx")) + workbook = load_workbook( + filename=os.path.join(self.test_directory, "file3.xlsx")) sheet = workbook.active self.assertEqual(sheet.cell(row=1, column=1).value, 'A simple') - + def test_case_4(self): # Test with a directory that doesn't exist with self.assertRaises(FileNotFoundError): f_309(directory_path="/invalid/directory/") - + def test_case_5(self): # Test with a directory that contains no .xlsx files os.makedirs(f"{self.test_directory}/empty_directory/", exist_ok=True) - processed_files_count = f_309(directory_path=f"{self.test_directory}/empty_directory/") + processed_files_count = f_309( + directory_path=f"{self.test_directory}/empty_directory/") self.assertEqual(processed_files_count, 0) diff --git a/data/raw/f_312_indraneil.py b/data/raw/f_312_indraneil.py index d9a15a3d..c857d7b0 100644 --- a/data/raw/f_312_indraneil.py +++ b/data/raw/f_312_indraneil.py @@ -45,7 +45,6 @@ def f_312(text, n, top_k): class TestCases(unittest.TestCase): def tearDown(self) -> None: plt.close('all') - return super().tearDown() def test_case_1(self): # Test with a simple text, bigram (n=2) and top 2 n-grams diff --git a/data/raw/f_316_indraneil.py b/data/raw/f_316_indraneil.py index a870f097..3c7f6e4c 100644 --- a/data/raw/f_316_indraneil.py +++ b/data/raw/f_316_indraneil.py @@ -66,11 +66,10 @@ def setUp(self): f.write("Dummy content for testing.") if os.path.exists(os.path.join(self.test_directory, "Interesting Files")): shutil.rmtree(os.path.join(self.test_directory, "Interesting Files")) - super(TestCases, self).setUp() def tearDown(self): - shutil.rmtree(self.test_directory) - super(TestCases, self).tearDown() + if os.path.exists(self.test_directory): + shutil.rmtree(self.test_directory) def test_caae_1(self): """Test if only files with 'like' or 'what' in their names are moved.""" diff --git a/data/raw/f_321_indraneil.py b/data/raw/f_321_indraneil.py index ec79d78d..bdba5054 100644 --- a/data/raw/f_321_indraneil.py +++ b/data/raw/f_321_indraneil.py @@ -67,11 +67,10 @@ def write_json_file(file_name, data): write_json_file('invalid.json', invalid_json_data) write_json_file('empty.json', empty_json_data) write_json_file('non_dict_list.json', non_dict_list_json_data) - super(TestCases, self).setUp() def tearDown(self): - shutil.rmtree(self.test_data_folder) - super(TestCases, self).tearDown() + if os.path.exists(self.test_data_folder): + shutil.rmtree(self.test_data_folder) def test_case_1(self): file_path = os.path.join(self.test_data_folder, 'valid.json') diff --git a/data/raw/f_323_indraneil.py b/data/raw/f_323_indraneil.py index 921d5a0a..77c42118 100644 --- a/data/raw/f_323_indraneil.py +++ b/data/raw/f_323_indraneil.py @@ -108,11 +108,10 @@ def setUp(self): # Empty directory for testing empty_dir = os.path.join(self.test_dir, 'empty_dir') os.makedirs(empty_dir, exist_ok=True) - super(TestCases, self).setUp() def tearDown(self): - shutil.rmtree(self.test_dir) - super(TestCases, self).tearDown() + if os.path.exists(self.test_dir): + shutil.rmtree(self.test_dir) def test_with_target_string(self): """Test with files containing the target string.""" From bff7f9045bfd40d1f7273c9e9f21cd1f8e88f018 Mon Sep 17 00:00:00 2001 From: BlankCheng <913501223@qq.com> Date: Sat, 18 May 2024 15:06:16 +0800 Subject: [PATCH 4/4] Fix doctest --- data/raw/f_681_xiaoheng.py | 1 + debug/f_681_xiaoheng.py | 103 +++++++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 debug/f_681_xiaoheng.py diff --git a/data/raw/f_681_xiaoheng.py b/data/raw/f_681_xiaoheng.py index 6ce61012..5ef264da 100644 --- a/data/raw/f_681_xiaoheng.py +++ b/data/raw/f_681_xiaoheng.py @@ -26,6 +26,7 @@ def f_681(): - random Example: + >>> random.seed(42) >>> hand, rank_counts = f_681() >>> print(hand) ['QH', '2C', '5D', '4H', 'QH'] diff --git a/debug/f_681_xiaoheng.py b/debug/f_681_xiaoheng.py new file mode 100644 index 00000000..5ef264da --- /dev/null +++ b/debug/f_681_xiaoheng.py @@ -0,0 +1,103 @@ +from collections import Counter +import random + +# Constants +HAND_RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] +SUITS = ['H', 'D', 'C', 'S'] + + +def f_681(): + """ + Generate a random poker hand consisting of five cards, and count the frequency of each card rank. + + The function creates a list of five cards where each card is a string made up of a rank and a suit (e.g., "10H" for Ten of Hearts). + It then counts the frequency of each card rank in the hand using a Counter dictionary. + + Parameters: + - None + + Returns: + tuple: A tuple containing two elements: + - hand (list): A list of five cards. + - rank_count (counter): A Counter dictionary of card ranks with their frequencies in the hand. + + Requirements: + - collections + - random + + Example: + >>> random.seed(42) + >>> hand, rank_counts = f_681() + >>> print(hand) + ['QH', '2C', '5D', '4H', 'QH'] + >>> print(rank_counts) + Counter({'Q': 2, '2': 1, '5': 1, '4': 1}) + """ + + hand = [] + for _ in range(5): + rank = random.choice(HAND_RANKS) + suit = random.choice(SUITS) + card = f'{rank}{suit}' + hand.append(card) + + rank_counts = Counter([card[:-1] for card in hand]) + + return hand, rank_counts + + +import unittest +from collections import Counter + +HAND_RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] +SUITS = ['H', 'D', 'C', 'S'] + + +class TestCases(unittest.TestCase): + def setUp(self) -> None: + random.seed(42) + + def test_poker_hand_length(self): + """Test if the poker hand has 5 cards.""" + hand, rank_counts = f_681() + self.assertEqual(len(hand), 5, "The poker hand should contain 5 cards.") + + def test_card_format(self): + """Test if each card in the hand is formatted correctly.""" + hand, rank_counts = f_681() + for card in hand: + self.assertIn(len(card), [2, 3], + "Each card should be a string of length 2 or 3.") + self.assertIn(card[:-1], HAND_RANKS, + "The rank of each card should be valid.") + self.assertIn(card[-1], SUITS, "The suit of each card should be valid.") + + def test_rank_counts_type(self): + """Test if rank_counts is of type Counter.""" + hand, rank_counts = f_681() + self.assertIsInstance(rank_counts, Counter, + "rank_counts should be a Counter dictionary.") + + def test_rank_counts_keys(self): + """Test if the keys of rank_counts are valid ranks.""" + hand, rank_counts = f_681() + for rank in rank_counts.keys(): + self.assertIn(rank, HAND_RANKS, "The ranks in rank_counts should be valid.") + + def test_rank_counts_values(self): + """Test if the values of rank_counts are integers.""" + hand, rank_counts = f_681() + for count in rank_counts.values(): + self.assertIsInstance(count, int, + "The counts in rank_counts should be integers.") + + +def run_tests(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(TestCases)) + runner = unittest.TextTestRunner() + runner.run(suite) + + +if __name__ == "__main__": + run_tests()