#!/usr/bin/env python3 import unittest from unittest.mock import patch, MagicMock import numpy as np from tmc import points from tmc.utils import load, get_out, patch_helper module_name = "src.stationary_initial_distribution" get_stationary_distributions = load(module_name, "get_stationary_distributions") main = load(module_name, "main") MarkovChain = load(module_name, "MarkovChain") kullback_leibler = load(module_name, "kullback_leibler") ph = patch_helper(module_name) # This solution to wrap a patched method comes originally from # https://stackoverflow.com/questions/25608107/python-mock-patching-a-method-without-obstructing-implementation def spy_decorator(method_to_decorate): mock = MagicMock() def wrapper(self, *args, **kwargs): mock(*args, **kwargs) return method_to_decorate(self, *args, **kwargs) wrapper.mock = mock return wrapper
#!/usr/bin/env python3 import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, get_out module_name = "src.acronyms" acronyms = load(module_name, "acronyms") @points('p01-18.1') class Acronyms(unittest.TestCase): def test_first(self): result = acronyms( """For the purposes of the EU General Data Protection Regulation (GDPR), the controller of your personal information is International Business Machines Corporation (IBM Corp.), 1 New Orchard Road, Armonk, New York, United States, unless indicated otherwise. Where IBM Corp. or a subsidiary it controls (not established in the European Economic Area (EEA)) is required to appoint a legal representative in the EEA, the representative for all such cases is IBM United Kingdom Limited, PO Box 41, North Harbour, Portsmouth, Hampshire, United Kingdom PO6 3AU.""" ) self.assertEqual(result, [ 'EU', 'GDPR', 'IBM', 'IBM', 'EEA', 'EEA', 'IBM', 'PO', 'PO6', '3AU' ]) def test_empty(self): result = acronyms("") self.assertEqual(result, [], msg="Empty list expected for empty input string!") if __name__ == '__main__': unittest.main()
#!/usr/bin/python3 import unittest import random from collections import Counter from tmc import points from tmc.utils import load, get_out context_probabilities = load('src.context_probabilities', 'context_probabilities') def random_nucleotide_sequence(length): nucs = "ACGT" result = [random.choice(nucs) for _ in range(length)] return "".join(result) @points('p07-11.1') class TestContextProbabilities(unittest.TestCase): def test_first(self): k = 2 s = "ATGATATCATCGACGATGTAG" d = context_probabilities(s, k) places = 3 self.assertAlmostEqual(d["TA"]['G'], 0.500000, places=places) self.assertAlmostEqual(d["TA"]['T'], 0.500000, places=places) self.assertAlmostEqual(d["TA"]['A'], 0.000000, places=places) self.assertAlmostEqual(d["TA"]['C'], 0.000000, places=places)
#!/usr/bin/env python3 import unittest from unittest.mock import patch import numpy as np import matplotlib.pyplot as plt from tmc import points from tmc.utils import load, get_stdout, patch_helper module_name = "src.radial_fade" radial_distance = load(module_name, "radial_distance") radial_mask = load(module_name, "radial_mask") radial_fade = load(module_name, "radial_fade") center = load(module_name, "center") main = load(module_name, "main") ph = patch_helper(module_name) class RadialFade(unittest.TestCase): @points('p03-12.1') def test_center(self): a = np.zeros((10, 11)) cy, cx = center(a) self.assertEqual( (cy, cx), (4.5, 5), msg="Wrong center for image of shape %s!" % (a.shape, )) a = np.zeros((10, 9, 3)) cy, cx = center(a)
#!/usr/bin/env python3 import numpy as np import unittest import timeit from unittest.mock import patch import copy from tmc import points from tmc.utils import load, get_out module_name="src.merge" merge = load(module_name, "merge") @points('p01-09.1') class Merge(unittest.TestCase): def test_non_mutating(self): L1_orig = [1,5,9,12] L2_orig = [2,6,10] L1 = copy.copy(L1_orig) L2 = copy.copy(L2_orig) result = merge(L1, L2) self.assertEqual(L1, L1_orig, msg="You are not allowed to modify the input lists!") self.assertEqual(L2, L2_orig, msg="You are not allowed to modify the input lists!") def test_first(self): L1 = [1,5,9,12] L2 = [2,6,10] result = merge(L1, L2)
#!/usr/bin/env python3 import unittest from unittest.mock import patch, MagicMock import pandas as pd from tmc import points from tmc.utils import load, get_stdout, patch_helper, spy_decorator module_name = "src.top_bands" top_bands = load(module_name, "top_bands") main = load(module_name, "main") ph = patch_helper(module_name) @points('p05-03.1') class TopBands(unittest.TestCase): def test_shape(self): df = top_bands() self.assertEqual(df.shape, (9, 13), msg="Incorrect shape!") def test_columns(self): df = top_bands() cols = [ 'Pos', 'LW', 'Title', 'Artist', 'Publisher', 'Peak Pos', 'WoC', 'Band', 'Singer', 'Lead guitar', 'Rhythm guitar', 'Bass', 'Drums' ] self.assertCountEqual(df.columns, cols, msg="Incorrect columns!") def test_calls(self):
def test_osa2_3_suoritukset_tulostuvat(self): output_alussa = get_stdout() try: koodi = """opiskelijat = {} lisaa_opiskelija(opiskelijat, "pekka") lisaa_suoritus(opiskelijat, "pekka", ("ohpe", 5)) lisaa_suoritus(opiskelijat, "pekka", ("tira", 3)) tulosta(opiskelijat, "pekka")""" lisaa_opiskelija = load(exercise, function1, 'fi') lisaa_suoritus = load(exercise, function3, 'fi') tulosta = load(exercise, function2, 'fi') opiskelijat = {} lisaa_opiskelija(opiskelijat, "pekka") lisaa_suoritus(opiskelijat, "pekka", ("ohpe", 5)) lisaa_suoritus(opiskelijat, "pekka", ("tira", 3)) tulosta(opiskelijat, "pekka") output_all = get_stdout().replace(output_alussa, '', 1) output = [l for l in output_all.split("\n") if len(l) > 0] expr1 = """pekka: suorituksia 2 kurssilta: ohpe 5 tira 3 keskiarvo 4.0""" expr2 = """pekka: suorituksia 2 kurssilta: tira 3 ohpe 5 keskiarvo 4.0""" exp1 = expr1.split('\n') exp2 = expr2.split('\n') except: self.assertTrue( False, f"Varmista, että seuraavan ohjelmakoodin suoritus onnistuu\n\{koodi}" ) self.assertFalse( len(output_all) == 0, f"Ohjelmasi pitäisi tulostaa {len(exp1)} riviä kun suoritetaan seuraava koodi:\n{koodi}\nNyt se ei tulosta mitään" ) self.assertEqual( len(output), len(exp1), f"Ohjelmasi pitäisi tulostaa {len(exp1)} riviä kun suoritetaan seuraava koodi:\n{koodi}\nNyt se tulostaa {len(output)} riviä:\n{output_all}" ) for i in range(len(exp1)): if exp1[i] == exp2[i]: self.assertTrue( output[i].rstrip() == exp1[i] or output[i].rstrip() == exp2[i], f"Kun suoritetaan seuraava koodi:\n{koodi}\nTulostettavan rivin numero {i+1} pitäisi olla:\n{exp1[i]}\nse on:\n{output[i]}" ) else: self.assertTrue( output[i].rstrip() == exp1[i] or output[i].rstrip() == exp2[i], f"Kun suoritetaan seuraava koodi:\n{koodi}\nTulostettavan rivin numero {i+1} pitäisi olla:\n{exp1[i]}\ntai\n{exp2[i]}\nse on:\n{output[i]}" )
#!/usr/bin/python3 import unittest #from p01_dna_to_rna import dna_to_rna from tmc import points from tmc.utils import load, get_out get_dict = load('src.codon_to_prob', 'get_dict') @points('p07-05.1') class TestCodonToProb(unittest.TestCase): def test_size(self): d = get_dict() self.assertEqual(len(d), 64) def test_content(self): d = get_dict() self.assertIn("UUU", d, msg="Codon UUU was not found in the dictionary!") self.assertEqual(d["UUU"], 0.46, msg="Incorrect probability of codon UUU!") self.assertIn("UCU", d, msg="Codon UCU was not found in the dictionary!") self.assertEqual(d["UCU"],
#!/usr/bin/env python3 import unittest from unittest.mock import patch, MagicMock import numpy as np import sklearn from tmc import points from tmc.utils import load, get_out, patch_helper module_name = 'src.word_classification' get_features = load(module_name, 'get_features') contains_valid_chars = load(module_name, 'contains_valid_chars') get_features_and_labels = load(module_name, 'get_features_and_labels') word_classification = load(module_name, 'word_classification') ph = patch_helper(module_name) class WordClassification(unittest.TestCase): @points('p06-03.1') def test_get_features(self): a = np.array(["abc", "zaka"]) f = get_features(a) self.assertEqual(f.shape[0], 2, msg="Feature array returned by get_features had incorrect shape!") self.assertEqual(f.shape[1], 29, msg="Feature array returned by get_features had incorrect shape!") self.assertEqual(f[0,0], 1, msg="Feature array returned by get_features had incorrect content in pos [0,0]!") self.assertEqual(f[0,1], 1, msg="Feature array returned by get_features had incorrect content in pos [0,1]!") self.assertEqual(f[0,2], 1, msg="Feature array returned by get_features had incorrect content in pos [0,2]!")
#!/usr/bin/env python3 import unittest from unittest.mock import patch import re import pandas as pd import os from tmc import points from tmc.utils import load, get_stdout, patch_helper module_name = "src.snow_depth" snow_depth = load(module_name, "snow_depth") main = load(module_name, "main") ph = patch_helper(module_name) @points('p04-09.1') class SnowDepth(unittest.TestCase): def test_value(self): ret_val = snow_depth() self.assertEqual(ret_val, 15.0, msg="Incorrect return value!") def test_output(self): main() out = get_stdout() pattern = r"Max snow depth:\s+\d+.\d" self.assertRegex(out, pattern, msg="Output is not in correct form!") def test_called(self):
#!/usr/bin/env python3 import unittest from unittest.mock import patch, MagicMock import pandas as pd from tmc import points from tmc.utils import load, get_out, patch_helper, spy_decorator module_name = "src.cyclists_per_day" cyclists_per_day = load(module_name, "cyclists_per_day") main = load(module_name, "main") ph = patch_helper(module_name) class CyclistsPerDay(unittest.TestCase): # @classmethod # def setUpClass(cls): # cls.df = cyclists_per_day() def setUp(self): self.df = cyclists_per_day() @points('p05-04.1') def test_shape(self): self.assertEqual( self.df.shape, (1547, 20), msg="cyclists_per_day returned DataFrame of wrong shape!")
import unittest, sys from tmc import points from tmc.utils import load, get_out sum = load('src.arithfuncs', 'sum') @points('python3_1') class TestCase(unittest.TestCase): @points('py3') def test_new(self): self.assertEqual(sum(1, 2), 3); if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 import unittest from unittest.mock import patch, MagicMock import pandas as pd import numpy as np from tmc import points from tmc.utils import load, get_stdout, patch_helper module_name = "src.bicycle_timeseries" bicycle_timeseries = load(module_name, "bicycle_timeseries") main = load(module_name, "main") ph = patch_helper(module_name) @points('p05-08.1') class BicycleTimeseries(unittest.TestCase): # @classmethod # def setUpClass(cls): # cls.df = bicycle_timeseries() def setUp(self): self.df = bicycle_timeseries() def test_shape(self): self.assertEqual(self.df.shape, (37128, 20), msg="Incorrect shape!") def test_columns(self):
#!/usr/bin/env python3 import unittest from unittest.mock import patch import numpy as np import pandas as pd from tmc import points from tmc.utils import load, get_out, patch_helper module_name="src.subsetting_by_positions" subsetting_by_positions = load(module_name, "subsetting_by_positions") main = load(module_name, "main") ph = patch_helper(module_name) @points('p04-08.1') class SubsettingByPositions(unittest.TestCase): def test_shape_and_columns(self): df = subsetting_by_positions() self.assertEqual(df.shape, (10,2), msg="The returned DataFrame had wrong shape!") #np.testing.assert_array_equal(df.index, range(10), err_msg="Incorrect index") np.testing.assert_array_equal(df.columns, ["Title", "Artist"], err_msg="Incorrect column names") def test_called(self): with patch(ph("subsetting_by_positions"), wraps=subsetting_by_positions) as psbp,\ patch(ph("pd.read_csv"), wraps=pd.read_csv) as prc: main()
import unittest from tmc import points from tmc.utils import load, get_stdout Tavara = load('src.tavara', 'Tavara') Matkalaukku = load('src.matkalaukku', 'Matkalaukku') @points('1.2') class MatkalaukkuTest(unittest.TestCase): def test_can_init(self): self.assertTrue(Matkalaukku(2), "Luokalla Matkalaukku tulee olla konstruktori joka ottaa yhden parametrin") def test_has_maksimipaino(self): self.assertEqual(1, Matkalaukku(1)._Matkalaukku__maksimipaino, "Matkalaukulla tulee olla piilotettu kenttä maksimipaino, " + "johon asetetaan konstruktorille annettu parametri") self.assertEqual(2, Matkalaukku(2)._Matkalaukku__maksimipaino, "Matkalaukulla tulee olla piilotettu kenttä maksimipaino, " + "johon asetetaan konstruktorille annettu parametri") def test_has_tavarat(self): self.assertTrue(hasattr(Matkalaukku(2), '_Matkalaukku__tavarat'), "Matkalaukulla tulee olla piilotettu kenttä 'tavarat'") def test_tavarat_empty_at_start(self):
#!/usr/bin/env python3 import unittest from tmc import points from tmc.utils import load, get_out import io import sys import uuid module_name = "src.list_vulnerabilities" get_vulnerabilities = load(module_name, "get_vulnerabilities") @points('3.4.1', '3.4.2', '3.4.3', '3.4.4', '3.4.5') class SafetyScanner(unittest.TestCase): def test_simple(self): db = open('test/snippet.json') result = get_vulnerabilities('acqusition', db) db.close() self.assertEqual(result, [('pyup.io-34978', '>0,<0', None)]) db = open('test/snippet.json') result = get_vulnerabilities('ampache', db) db.close() self.assertEqual(result, \ [('pyup.io-37866', '<3.6-alpha5', None), \ ('pyup.io-37865', '<3.8.0', 'CVE-2014-8620'), \ ('pyup.io-37864', '<3.8.2', None), \ ('pyup.io-37863', '<4.0.0', 'CVE-2019-12385, CVE-2019-12386')])
import unittest, sys from tmc import points from tmc.utils import load, get_out Tavara = load('src.tavara', 'Tavara') Matkalaukku = load('src.matkalaukku', 'Matkalaukku') Lastiruuma = load('src.lastiruuma', 'Lastiruuma') @points('1.3') class LastiruumaTest(unittest.TestCase): def test_can_init(self): self.assertTrue(Lastiruuma(2), "Luokalla Lastiruuma tulee olla konstruktori joka ottaa yhden parametrin") def test_has_maksimipaino(self): self.assertEqual(1, Lastiruuma(1)._Lastiruuma__maksimipaino, "Lastiruumalla tulee olla piilotettu kenttä maksimipaino, johon asetetaan konstruktorille annettu parametri") self.assertEqual(2, Lastiruuma(2)._Lastiruuma__maksimipaino, "Lastiruumalla tulee olla piilotettu kenttä maksimipaino, johon asetetaan konstruktorille annettu parametri") def test_has_matkalaukut(self): self.assertTrue(hasattr(Lastiruuma(2), '_Lastiruuma__matkalaukut'), "Lastiruumalla tulee olla piilotettu kenttä 'matkalaukut'") def test_tavarat_empty_at_start(self): self.assertEquals(0,
#!/usr/bin/env python3 import unittest from unittest.mock import patch from tmc import points import re from tmc.utils import load, get_stdout, patch_helper module_name = "src.red_green_blue" red_green_blue = load(module_name, "red_green_blue") ph = patch_helper(module_name) @points('p02-03.1') class RedGreenBlue(unittest.TestCase): def test_size(self): result = red_green_blue() self.assertIsInstance( result, list, f"red_green_blue should return a list. Got {type(result)}.") self.assertEqual(len(result), 753, "Wrong number of strings in the returned list!") for s in result: self.assertIsInstance( s, str, f"red_green_blue should return a list of string. Found {type(s)} in list." ) self.assertEqual( len(s.split("\t")), 4,
import unittest from tmc import points from tmc.utils import load module_name = "src.passing_exercise" hello = load(module_name, "hello") @points("1.passing_exercise") class PassingExercise(unittest.TestCase): def test_passing(self): self.assertEqual(hello(), "Hello world!") if __name__ == "__main__": unittest.main()
#!/usr/bin/env python3 import unittest from unittest.mock import patch import numpy as np import pandas as pd from tmc import points from tmc.utils import load, get_out, patch_helper module_name = "src.last_week" last_week = load(module_name, "last_week") ph = patch_helper(module_name) class LastWeek(unittest.TestCase): # @classmethod # def setUpClass(cls): # cls.df = last_week() def setUp(self): self.df = last_week() @points('p04-15.1') def check_column(self, col, correct, nans, column_name): for row in range(1, 41): if row in nans: self.assertTrue(pd.isnull(col.iloc[row - 1]), msg="Expected a nan on row %i column %s!" %
#!/usr/bin/env python3 import numpy as np import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, get_stdout, patch_helper, spy_decorator module_name = "src.interleave" interleave = load(module_name, "interleave") ph = patch_helper(module_name) @points('p01-11.1') class Interleave(unittest.TestCase): def test_first(self): L1 = [1, 2, 3] L2 = [20, 30, 40] L3 = ['a', 'b', 'c'] result = interleave(L1, L2, L3) self.assertIsInstance( result, list, f"interleave should return a list. Got {type(result)}") self.assertEqual(result, [1, 20, 'a', 2, 30, 'b', 3, 40, 'c'], msg="Incorrect result for input lists %s, %s, %s!" % (L1, L2, L3)) def test_random(self):
#!/usr/bin/env python3 import unittest from unittest.mock import patch, MagicMock from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB import sklearn from tmc import points from tmc.utils import load, get_out, patch_helper, spy_decorator module_name = "src.plant_classification" plant_classification = load(module_name, 'plant_classification') main = load(module_name, "main") ph = patch_helper(module_name) @points('p06-02.1') class PlantClassification(unittest.TestCase): def test_correctness(self): acc = plant_classification() self.assertAlmostEqual(acc, 0.966667, places=5, msg="Incorrect accuracy score!") def test_accuracy_called(self): score_method = spy_decorator(sklearn.naive_bayes.GaussianNB.score, "score")
def test_2_paluuarvon_tyyppi(self): pisin = load(exercise, function, 'fi') val = pisin(["ab","a"]) self.assertTrue(type(val) == str, f'Funktio {function} ei palauta merkkijonoa kutsulla pisin(["ab","a"])')
def test_2_paluuarvon_tyyppi(self): transponoi = load(exercise, function, 'fi') val = transponoi([[1, 2], [1, 2]]) self.assertTrue(val == None, f"Funktion {function} ei tulisi palauttaa arvoa.")
#!/usr/bin/env python3 import unittest from unittest.mock import patch import numpy as np import matplotlib.pyplot as plt from tmc import points from tmc.utils import load, get_stdout, patch_helper module_name = "src.to_grayscale" to_grayscale = load(module_name, "to_grayscale") to_red = load(module_name, "to_red") to_green = load(module_name, "to_green") to_blue = load(module_name, "to_blue") main = load(module_name, "main") ph = patch_helper(module_name) class ToGrayscale(unittest.TestCase): def setUp(self): self.n = 100 self.m = 100 self.a = np.random.randint(0, 256, (self.n, self.m, 3)) @points('p03-11.1') def test_gray(self): g = to_grayscale(self.a) self.assertEqual(
#!/usr/bin/env python3 import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, get_out module_name = "src.correlation" correlations = load(module_name, "correlations") lengths = load(module_name, "lengths") def patch_name(m, d): import importlib parts = d.split(".") try: getattr(importlib.import_module(m), parts[-1]) p = ".".join([m, parts[-1]]) except ModuleNotFoundError: raise except AttributeError: if len(parts) == 1: raise try: getattr(importlib.import_module(m), parts[-2]) p = ".".join([m] + parts[-2:]) except AttributeError: if len(parts) == 2: raise
#!/usr/bin/env python3 import re import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, get_stdout module_name = "src.triple_square" main = load(module_name, "main") triple = load(module_name, "triple") square = load(module_name, "square") class TripleSquare(unittest.TestCase): def content_helper(self, countlist): main() result = get_stdout().split('\n') l = len(result) self.assertIn(l, countlist, msg="Wrong number of printed lines: %i!" % l) for i, line in zip(range(l), result): j = i + 1 pattern = r"triple\((\d+)\)==(\d+) square\((\d+)\)==(\d+)" self.assertRegex(line, pattern, msg="The output line was not in correct format!") m = re.match(pattern, line)
#!/usr/bin/env python3 import unittest from unittest.mock import patch import pandas as pd import re from tmc import points from tmc.utils import load, get_stdout, patch_helper module_name = "src.growing_municipalities" growing_municipalities = load(module_name, "growing_municipalities") main = load(module_name, "main") ph = patch_helper(module_name) @points('p04-06.1') class GrowingMunicipalities(unittest.TestCase): # @classmethod # def setUpClass(cls): # cls.df = pd.read_csv(get_path("municipal.tsv"), # index_col=0, sep="\t") # cls.df = cls.df["Akaa":"Äänekoski"] # cls.c = "Population change from the previous year, %" def setUp(self): self.df = pd.read_csv("src/municipal.tsv", index_col=0, sep="\t") self.df = self.df["Akaa":"Äänekoski"] self.c = "Population change from the previous year, %"
#!/usr/bin/env python3 import numpy as np import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, get_out module_name = "src.positive_list" positive_list = load(module_name, "positive_list") @points('p01-17.1') class PositiveList(unittest.TestCase): def test_first(self): L = [2, -2, 0, 1, -7] result = positive_list(L) self.assertIsInstance( result, list, f"positive_list should return a list. Got {type(result)}") self.assertEqual(result, [2, 1], msg="Wrong result for list %s!" % L) def test_random(self): for i in range(4): L = np.random.randint(-100, 100, 50) result = positive_list(L) self.assertIsInstance( result, list, f"positive_list should return a list. Got {type(result)}")
import unittest from tmc import points from tmc.utils import load Tavara = load('src.tavara', 'Tavara') @points('1.1') class TavaraTest(unittest.TestCase): def test_can_init(self): self.assertTrue( Tavara("a", 1), "Luokalla Tavara tulee olla konstruktori joka ottaa kaksi arvoa") def test_has_name(self): self.assertEqual( "Kivi", Tavara("Kivi", 1).nimi, "Tavaralla tulee olla muuttuja nimi johon asetetaan konstruktorin ensimmäinen parametri" ) self.assertEqual( "Tiili", Tavara("Tiili", 1).nimi, "Tavaralla tulee olla muuttuja nimi johon asetetaan konstruktorin ensimmäinen parametri" ) def test_has_name(self): self.assertEqual( 1,
import unittest from tmc import points from tmc.utils import load Tavara = load('src.tavara', 'Tavara') @points('1.1') class TavaraTest(unittest.TestCase): def test_can_init(self): self.assertTrue(Tavara("a", 1), "Luokalla Tavara tulee olla konstruktori joka ottaa kaksi arvoa") def test_has_name(self): self.assertEqual("Kivi", Tavara("Kivi", 1).nimi, "Tavaralla tulee olla muuttuja nimi johon asetetaan konstruktorin ensimmäinen parametri") self.assertEqual("Tiili", Tavara("Tiili", 1).nimi, "Tavaralla tulee olla muuttuja nimi johon asetetaan konstruktorin ensimmäinen parametri") def test_has_name(self): self.assertEqual(1, Tavara("Kivi", 1).paino, "Tavaralla tulee olla muuttuja paino johon asetetaan konstruktorin toinen parametri") self.assertEqual(2, Tavara("Tiili", 2).paino, "Tavaralla tulee olla muuttuja paino johon asetetaan konstruktorin toinen parametri")
#!/usr/bin/env python3 import unittest from unittest.mock import patch import pandas as pd import numpy as np from tmc import points from tmc.utils import load, get_out, patch_helper module_name = "src.inverse_series" inverse_series = load(module_name, "inverse_series") main = load(module_name, "main") ph = patch_helper(module_name) @points('p03-15.1') class InverseSeries(unittest.TestCase): def test_first(self): L = [1, 2, 3, 1] ind = list("abcd") s = pd.Series(L, index=ind) t = inverse_series(s) np.testing.assert_array_equal(t.values, ind, err_msg="Values were incorrect!") np.testing.assert_array_equal(t.index, L, err_msg="Index was incorrect!")
import unittest from tmc import points from tmc.utils import load, get_stdout Tavara = load("src.tavara", "Tavara") Matkalaukku = load("src.matkalaukku", "Matkalaukku") Lastiruuma = load("src.lastiruuma", "Lastiruuma") @points("1.3") class LastiruumaTest(unittest.TestCase): def test_can_init(self): self.assertTrue(Lastiruuma(2), "Luokalla Lastiruuma tulee olla konstruktori joka ottaa yhden parametrin") def test_has_maksimipaino(self): self.assertEqual( 1, Lastiruuma(1)._Lastiruuma__maksimipaino, "Lastiruumalla tulee olla piilotettu kenttä maksimipaino, " + "johon asetetaan konstruktorille annettu parametri", ) self.assertEqual( 2, Lastiruuma(2)._Lastiruuma__maksimipaino, "Lastiruumalla tulee olla piilotettu kenttä maksimipaino, " + "johon asetetaan konstruktorille annettu parametri", ) def test_has_matkalaukut(self):
#!/usr/bin/env python3 import sys import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, get_out module_name = "src.file_count" file_count = load(module_name, "file_count") main = load(module_name, "main") def get_path(filename): import sys import os return os.path.join(os.path.dirname(sys.argv[0]), "..", "src", filename) class FileCount(unittest.TestCase): @points('p02-06.1') def test_first(self): l, w, c = file_count(get_path("test.txt")) self.assertEqual(l, 8, msg="Wrong number of lines for file 'test.txt'!") self.assertEqual(w, 105, msg="Wrong number of words for file 'test.txt'!")
import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, get_stdout Greeter = load('src.greeter', 'Greeter') @points('1.0') class GreeterTest(unittest.TestCase): def test_greets(self): with patch('builtins.input', side_effect=['Make']) as prompt: g = Greeter() g.greet() output = get_stdout() self.assertTrue("Hello Make" in output) prompt.assert_called_once_with("Who are you?")
#!/usr/bin/env python3 import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, get_out module_name = "src.compliment" main = load(module_name, "main") @points('p01-02.1') class Compliment(unittest.TestCase): def test_first(self): with patch('builtins.input', side_effect=['France']) as prompt: main() output = get_out() self.assertEqual( "I have heard that France is a beautiful country.", output) prompt.assert_called_once_with("What country are you from? ") if __name__ == '__main__': unittest.main()