class TestParserInitialization(BaseTestCase): UNKNOWN_LANGUAGES_EXCEPTION_RE = re.compile(u"Unknown language\(s\): (.+)") def setUp(self): super(TestParserInitialization, self).setUp() self.result = NotImplemented @parameterized.expand([ param(['ur', 'li'], unknown_languages=[u'ur', u'li']), param(['ur', 'en'], unknown_languages=[u'ur']), param(['pk'], unknown_languages=[u'pk']), ]) def test_should_raise_error_when_unknown_language_given(self, shortnames, unknown_languages): self.when_parser_is_initialized(languages=shortnames) self.then_languages_are_unknown(unknown_languages) def when_parser_is_initialized(self, **params): try: self.parser = date.DateDataParser(**params) except Exception as error: self.error = error def then_languages_are_unknown(self, unknown_languages): self.assertIsInstance(self.error, ValueError) match = self.UNKNOWN_LANGUAGES_EXCEPTION_RE.match(str(self.error)) self.assertTrue(match) languages = match.group(1).split(", ") six.assertCountEqual(self, languages, [repr(l) for l in unknown_languages])
class Test_Orbitals(object): def setUp(self): self.mol = pg.Molecule(folder_obj=pg.get_test_folder(), opt_fname='CJS1_emim-cl_F_6-311+g-d-p-_gd3bj_opt-modredundant_unfrz.log', nbo_fname='CJS1_emim-cl_F_6-311+g-d-p-_gd3bj_pop-nbo-full-_unfrz.log', atom_groups={'emim':range(1,20), 'cl':[20]}, alignto=[3,2,1]) def test_orbital_count(self): that.assert_equal(self.mol.get_orbital_count(), 272) def test_orbital_homo_lumo(self): that.assert_equal(self.mol.get_orbital_homo_lumo(), (39,40)) @parameterized([param(1,-101.39532), param(10, -9.30938), param(39, -0.19600), param(40, -0.04310), param(272, 215.85458), ]) def test_orbital_energies(self, orbital, energy): that.assert_almost_equal(self.mol.get_orbital_energies(orbital, eunits='hartree')[0], energy) def test_plot_dos(self): ax = self.mol.plot_dos(lbound=-20, ubound=10) def test_yield_orbital_images_no_isos(self): pg.isosurface.get_isosurface = mock_isosurface self.mol.yield_orbital_images(1)
class TestExactLanguages(BaseLanguageDetectorTestCase): __test__ = True @parameterized.expand([ param("01-01-12", ['en', 'fr']), param("01-01-12", ['tr', 'ar']), param("01-01-12", ['ru', 'fr', 'en', 'pl']), param("01-01-12", ['en']), ]) def test_exact_languages(self, datetime_string, shortnames): self.given_string(datetime_string) self.given_known_languages(shortnames) self.given_detector() self.when_using_exact_languages() self.then_exact_languages_were_filtered(shortnames) def given_known_languages(self, shortnames): self.known_languages = [self.language_loader.get_language(shortname) for shortname in shortnames] def given_detector(self): self.assertIsInstance(self.known_languages, list, "Require a list of languages to initialize") self.assertGreaterEqual(len(self.known_languages), 1, "Could only be initialized with one or more languages") self.detector = ExactLanguages(languages=self.known_languages) def when_using_exact_languages(self): self.exact_languages = self.detector.iterate_applicable_languages(self.datetime_string, modify=True) def then_exact_languages_were_filtered(self, shortnames): self.assertEqual(set(shortnames), set([lang.shortname for lang in self.exact_languages]))
class TestWithDifferentLambdaRuntimeZips(InvokeIntegBase): def setUp(self): self.template_path = os.path.join(self.test_data_path, "invoke", "runtimes", "template.yaml") # Don't delete on close. Need the file to be present for tests to run. events_file = tempfile.NamedTemporaryFile(delete=False) events_file.write(b'"yolo"') # Just empty event events_file.flush() events_file.close() self.events_file_path = events_file.name def tearDown(self): os.remove(self.events_file_path) @parameterized.expand([param("Go1xFunction"), param("Java8Function")]) def test_runtime_zip(self, function_name): command_list = self.get_command_list(function_name, template_path=self.template_path, event_path=self.events_file_path) process = Popen(command_list, stdout=PIPE) return_code = process.wait() self.assertEquals(return_code, 0) process_stdout = b"".join(process.stdout.readlines()).strip() self.assertEquals(process_stdout.decode('utf-8'), '"Hello World"')
class TestTimeZoneConversion(BaseTestCase): def setUp(self): super(TestTimeZoneConversion, self).setUp() self.settings = {} self.parser = parse self.result = NotImplemented @parameterized.expand([ param('2015-12-31 10:04 AM', 'Asia/Karachi', 'UTC', datetime(2015, 12, 31, 5, 4)), param('2015-12-30 10:04 AM', 'Asia/Karachi', '+0200', datetime(2015, 12, 30, 7, 4)), ]) def test_timezone_conversion(self, datestring, from_tz, to_tz, expected): self.given_from_timezone(from_tz) self.given_to_timezone(to_tz) self.when_date_is_parsed(datestring) self.then_date_is(expected) def given_from_timezone(self, timezone): self.settings['TIMEZONE'] = timezone def given_to_timezone(self, timezone): self.settings['TO_TIMEZONE'] = timezone def when_date_is_parsed(self, datestring): self.result = self.parser(datestring, settings=self.settings) def then_date_is(self, date): self.assertEqual(date, self.result)
class TestWithDifferentLambdaRuntimeZips(InvokeIntegBase): template = Path("runtimes", "template.yaml") def setUp(self): # Don't delete on close. Need the file to be present for tests to run. events_file = tempfile.NamedTemporaryFile(delete=False) events_file.write(b'"yolo"') # Just empty event events_file.flush() events_file.close() self.events_file_path = events_file.name def tearDown(self): os.remove(self.events_file_path) @pytest.mark.timeout(timeout=300, method="thread") @parameterized.expand([param("Go1xFunction"), param("Java8Function")]) def test_runtime_zip(self, function_name): command_list = self.get_command_list(function_name, template_path=self.template_path, event_path=self.events_file_path) process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise self.assertEqual(process.returncode, 0) process_stdout = stdout.strip() self.assertEqual(process_stdout.decode("utf-8"), '"Hello World"') @pytest.mark.timeout(timeout=300, method="thread") def test_custom_provided_runtime(self): command_list = self.get_command_list("CustomBashFunction", template_path=self.template_path, event_path=self.events_file_path) command_list = command_list + ["--skip-pull-image"] process = Popen(command_list, stdout=PIPE) try: stdout, _ = process.communicate(timeout=TIMEOUT) except TimeoutExpired: process.kill() raise self.assertEqual(process.returncode, 0) process_stdout = stdout.strip() self.assertEqual( process_stdout.decode("utf-8"), '{"body":"hello 曰有冥 world 🐿","statusCode":200,"headers":{}}')
class ExactLanguagesTest(BaseTestCase): def setUp(self): super(ExactLanguagesTest, self).setUp() self.parser = NotImplemented self.detected_languages = NotImplemented def test_languages_passed_in_constructor_should_not_be_none(self): self.when_parser_is_constructed(languages=None) self.then_error_was_raised( ValueError, ['language cannot be None for ExactLanguages']) @parameterized.expand([ param(languages=['es'], date_strings=["13 Ago, 2014"]), param(languages=['es'], date_strings=["13 Septiembre, 2014"]), param(languages=['es'], date_strings=["13/03/2014"]), param(languages=['es'], date_strings=["11/03/2014"]), ]) def test_parse_date_in_exact_language(self, languages, date_strings): self.given_parser(languages) self.when_languages_are_detected(date_strings) self.then_detected_languages_are(languages) @parameterized.expand([ param(languages=['es'], date_strings=["13 Setembro, 2014"]), ]) def test_reject_dates_in_other_languages(self, languages, date_strings): self.given_parser(languages=languages) self.when_languages_are_detected(date_strings) self.then_detected_languages_are([]) def given_parser(self, languages): language_map = default_language_loader.get_language_map() languages = [language_map[language] for language in languages] self.parser = ExactLanguages(languages) def when_languages_are_detected(self, date_strings, modify=False): assert not isinstance(date_strings, six.string_types) for date_string in date_strings: detected_languages = list( self.parser.iterate_applicable_languages(date_string, modify=modify, settings=settings)) self.detected_languages = detected_languages def when_parser_is_constructed(self, languages): try: ExactLanguages(languages) except Exception as error: self.error = error def then_detected_languages_are(self, expected_languages): shortnames = map(attrgetter('shortname'), self.detected_languages) six.assertCountEqual(self, expected_languages, shortnames)
class TestGetPythonVersion(TestCase): """Test cases for obtaining the python version.""" @parameterized.expand([ param(1, "{0}".format(sys.version_info[0])), param(2, "{0}.{1}".format(sys.version_info[0], sys.version_info[1])), param( 3, "{0}.{1}.{2}".format(sys.version_info[0], sys.version_info[1], sys.version_info[2])) ]) def test_get_python_version_at_precision(self, precision, expected_version): """Get python version at precision.""" self.assertEqual(expected_version, python_util.get_python_version(util, precision))
class TestTimeParser(BaseTestCase): @parameterized.expand([ param(date_string=u"11:30:14", timeobj=time(11, 30, 14)), param(date_string=u"11:30", timeobj=time(11, 30)), param(date_string=u"11:30 PM", timeobj=time(23, 30)), param(date_string=u"1:30 AM", timeobj=time(1, 30)), param(date_string=u"1:30:15.330 AM", timeobj=time(1, 30, 15, 330000)), param(date_string=u"1:30:15.330 PM", timeobj=time(13, 30, 15, 330000)), param(date_string=u"1:30:15.3301 PM", timeobj=time(13, 30, 15, 330100)), param(date_string=u"14:30:15.330100", timeobj=time(14, 30, 15, 330100)), ]) def test_time_is_parsed(self, date_string, timeobj): self.given_parser() self.when_time_is_parsed(date_string) self.then_time_exactly_is(timeobj) def given_parser(self): self.parser = time_parser def when_time_is_parsed(self, datestring): self.result = self.parser(datestring) def then_time_exactly_is(self, timeobj): self.assertEqual(self.result, timeobj)
class TestDefaultDict(unittest.TestCase): @parameterized.expand( [ param(set, (lambda x: x.add(1))), param(list, (lambda x: x.append(1))), param(dict, (lambda x: x.update({'key': 1}))) ] ) def test_default_dict(self, default, operate): obj = DefaultDict(default) operate(obj['test']) print '{} {} {}'.format('#' * 25, 'Default dict', '#' * 25) print obj, '\n'
class TestChanges(InvenioTestCase): """Test if desired changes occured.""" @parameterized.expand(( ('space_sep' , 'this is erratum for' , {'ERRATUM'}) , ('nothing' , 'this is nothing' , set()) , ('colon_sep' , 'corrigendum: something' , {'CORRIGENDUM'}) , ('two' , 'corrigendum: erratum' , {'CORRIGENDUM' , 'ERRATUM'}) , )) def test_finding_of_collections_in_title(self, _, title, expected_collections): _collections_in_title = find_erratum._collections_in_title collections_found = _collections_in_title(title) self.assertEquals(collections_found, expected_collections) @parameterized.expand(( # test_name , record , expected_record ('exists_erratum' , {'collections': {'additional': 'ERRATUM'}} , {'ERRATUM'} , {'collections': {'additional': 'ERRATUM'}}) , ('no_additional' , {'collections': {'primary': 'coll'}} , set() , {'collections': {'primary': 'coll'}}) , ('no_collections' , {} , {'CORRIGENDUM'} , {'collections': {'additional': 'CORRIGENDUM'}}) , param('two_collections' , {} , {'CORRIGENDUM', 'ERRATUM'} , expected_exception=KeyError) , )) def test_tetriary_collection_is_correctly_set(self, _, record, found_collections, expected_record=None, expected_exception=None): _set_collections_in_record = find_erratum._set_collections_in_record run_check = lambda: _set_collections_in_record(record, found_collections) if expected_exception: with self.assertRaises(expected_exception): run_check() else: returned_record = run_check() self.assertEqual(returned_record, expected_record)
class TestWithDifferentLambdaRuntimeZips(InvokeIntegBase): template = Path("runtimes", "template.yaml") def setUp(self): # Don't delete on close. Need the file to be present for tests to run. events_file = tempfile.NamedTemporaryFile(delete=False) events_file.write(b'"yolo"') # Just empty event events_file.flush() events_file.close() self.events_file_path = events_file.name def tearDown(self): os.remove(self.events_file_path) @parameterized.expand([ param("Go1xFunction"), param("Java8Function") ]) def test_runtime_zip(self, function_name): command_list = self.get_command_list(function_name, template_path=self.template_path, event_path=self.events_file_path) process = Popen(command_list, stdout=PIPE) return_code = process.wait() self.assertEquals(return_code, 0) process_stdout = b"".join(process.stdout.readlines()).strip() self.assertEquals(process_stdout.decode('utf-8'), '"Hello World"') def test_custom_provided_runtime(self): command_list = self.get_command_list("CustomBashFunction", template_path=self.template_path, event_path=self.events_file_path) command_list = command_list + ["--skip-pull-image"] process = Popen(command_list, stdout=PIPE) return_code = process.wait() self.assertEquals(return_code, 0) process_stdout = b"".join(process.stdout.readlines()).strip() self.assertEquals(process_stdout.decode('utf-8'), u'{"body":"hello 曰有冥 world 🐿","statusCode":200,"headers":{}}')
class TestPPrint(PPrintppTestBase): uni_safe = u"\xe9 \u6f02 \u0e4f \u2661" uni_unsafe = u"\u200a \u0302 \n" slashed = lambda s: u"%s'%s'" %( p.u_prefix, s.encode("ascii", "backslashreplace").decode("ascii").replace("\n", "\\n") ) @parameterized([ param("safe", uni_safe, "%s'%s'" %(p.u_prefix, uni_safe)), param("unsafe", uni_unsafe, slashed(uni_unsafe)), param("encoding-aware", uni_safe, slashed(uni_safe), encoding="ascii"), param("high-end-chars", u"\U0002F9B2", slashed(u"\U0002F9B2"), encoding="ascii"), ]) def test_unicode(self, name, input, expected, encoding="utf-8"): stream = p.TextIO(encoding=encoding) p.pprint(input, stream=stream) assert_equal(stream.getvalue().rstrip("\n"), expected) @parameterized([ param("both", "'\"", u"'\\'\"'"), param("single", "'", u'"\'"'), param("double", '"', u"'\"'"), ]) def test_quotes(self, name, input, expected): stream = p.TextIO() p.pprint(input, stream=stream) assert_equal(stream.getvalue().rstrip("\n"), expected)
class TestHijriParser(BaseTestCase): def setUp(self): super(TestHijriParser, self).setUp() self.result = NotImplemented self.date_string = NotImplemented self.parser = NotImplemented self.translated = NotImplemented def when_date_is_given(self, dt_string, date_formats, languages): self.date_string = dt_string self.parser = HijriCalendar(dt_string) self.result = self.parser.get_date() def then_parsed_datetime_is(self, dt): self.assertEqual(dt, self.result['date_obj']) @parameterized.expand([ param(dt_string="14-09-1432 هـ, 09:40 صباحاً", dt_obj=datetime(2011, 8, 14, 9, 40)), param(dt_string="20-02-1430 هـ, 07:21 صباحاً", dt_obj=datetime(2009, 2, 15, 7, 21)), param(dt_string="11-08-1434 هـ, 09:38 صباحاً", dt_obj=datetime(2013, 6, 20, 9, 38)), param(dt_string=" 17-01-1437 هـ 08:30 مساءً", dt_obj=datetime(2015, 10, 30, 20, 30)), param(dt_string="29-02-1433 هـ, 06:22 صباحاً", dt_obj=datetime(2012, 1, 23, 6, 22)), param(dt_string="30-02-1433", dt_obj=datetime(2012, 1, 24)), param(dt_string="04-03-1433 هـ, 10:08 مساءً", dt_obj=datetime(2012, 1, 27, 22, 8)), ]) def test_datetime_parsing(self, dt_string, dt_obj, date_formats=None, languages=None): from dateparser.conf import settings settings.DATE_ORDER = 'DMY' self.when_date_is_given(dt_string, date_formats, languages) self.then_parsed_datetime_is(dt_obj) settings.DATE_ORDER = 'MDY'
class TestParseFunction(BaseTestCase): def setUp(self): super(TestParseFunction, self).setUp() self.result = NotImplemented @parameterized.expand([ param(date_string="24 de Janeiro de 2014", expected_date=date(2014, 1, 24)), param(date_string="2 de Enero de 2013", expected_date=date(2013, 1, 2)), param(date_string="January 25, 2014", expected_date=date(2014, 1, 25)), ]) def test_parse_dates_in_different_languages(self, date_string, expected_date): self.when_date_is_parsed(date_string) self.then_parsed_date_is(expected_date) @parameterized.expand([ param(date_string="24 de Janeiro de 2014", languages=['pt'], expected_date=date(2014, 1, 24)), ]) def test_dates_which_match_languages_are_parsed(self, date_string, languages, expected_date): self.when_date_is_parsed(date_string, languages=languages) self.then_parsed_date_is(expected_date) @parameterized.expand([ param(date_string="January 24, 2014", languages=['pt']), ]) def test_dates_which_do_not_match_languages_are_not_parsed( self, date_string, languages): self.when_date_is_parsed(date_string, languages=languages) self.then_date_was_not_parsed() def when_date_is_parsed(self, date_string, languages=None): self.result = dateparser.parse(date_string, languages=languages) def then_parsed_date_is(self, expected_date): self.assertEquals(self.result, datetime.combine(expected_date, datetime.min.time())) def then_date_was_not_parsed(self): self.assertIsNone(self.result)
class TestUtils(BaseTestCase): def setUp(self): super(TestUtils, self).setUp() self.date_format = None self.result = None def given_date_format(self, date_format): self.date_format = date_format def when_date_seperator_is_parsed(self): self.result = find_date_separator(self.date_format) def then_date_seperator_is(self, sep): self.assertEqual(self.result, sep) @parameterized.expand([ param(date_format=fmt.format(sep=sep), expected_sep=sep) for (fmt, sep) in itertools.product( ['%d{sep}%m{sep}%Y', '%d{sep}%m{sep}%Y %H:%M'], ['/', '.', '-', ':']) ]) def test_separator_extraction(self, date_format, expected_sep): self.given_date_format(date_format) self.when_date_seperator_is_parsed() self.then_date_seperator_is(expected_sep) @parameterized.expand([ param(datetime(2015, 12, 12), timezone='UTC', zone='UTC'), param(datetime(2015, 12, 12), timezone='Asia/Karachi', zone='Asia/Karachi'), ]) def test_localize_timezone(self, date, timezone, zone): tzaware_dt = localize_timezone(date, timezone) self.assertEqual(tzaware_dt.tzinfo.zone, zone) @parameterized.expand([ param(datetime(2015, 12, 12, 10, 12), timezone='Asia/Karachi', expected=datetime(2015, 12, 12, 15, 12)), param(datetime(2015, 12, 12, 10, 12), timezone='-0500', expected=datetime(2015, 12, 12, 5, 12)), ]) def test_apply_timezone(self, date, timezone, expected): result = apply_timezone(date, timezone) result = result.replace(tzinfo=None) self.assertEqual(expected, result)
class TestPersianDate(BaseTestCase): def setUp(self): super(TestPersianDate, self).setUp() self.persian_date = NotImplemented def when_date_is_given(self, year, month, day): self.persian_date = PersianDate(year, month, day) def then_weekday_is(self, weekday): self.assertEqual(self.persian_date.weekday(), weekday) @parameterized.expand([ param(year=1348, month=1, day=3, weekday=0), param(year=1348, month=2, day=28, weekday=0), param(year=1348, month=3, day=27, weekday=2), param(year=1348, month=4, day=11, weekday=3), ]) def test_weekday(self, year, month, day, weekday): self.when_date_is_given(year, month, day) self.then_weekday_is(weekday)
class TestLocalTZOffset(BaseTestCase): def setUp(self): super(TestLocalTZOffset, self).setUp() self.timezone_offset = NotImplemented @parameterized.expand([ param(utc='2014-08-20 4:32', local='2014-08-20 8:32', offset=+4), param(utc='2052-01-02 11:07', local='2052-01-02 10:07', offset=-1), param(utc='2013-12-31 23:59', local='2014-01-01 00:29', offset=+0.5), param(utc='2011-07-14 11:59', local='2011-07-13 23:59', offset=-12), param(utc='2014-10-18 17:41', local='2014-10-18 17:41', offset=0), ]) def test_timezone_offset_calculation(self, utc, local, offset): self.given_utc_time(utc) self.given_local_time(local) self.when_offset_popped_from_string() self.then_offset_is(offset) def given_utc_time(self, datetime_string): self._given_time(datetime_string, 'utcnow') def given_local_time(self, datetime_string): self._given_time(datetime_string, 'now') def when_offset_popped_from_string(self): self.timezone_offset = get_local_tz_offset() def then_offset_is(self, expected_offset): delta = timedelta( seconds=3600 * expected_offset) if expected_offset is not None else None self.assertEqual(delta, self.timezone_offset) def _given_time(self, datetime_string, getter_name): datetime_cls = dateparser.timezone_parser.datetime if not isinstance(datetime_cls, Mock): datetime_cls = Mock(wraps=datetime) datetime_obj = datetime.strptime(datetime_string, '%Y-%m-%d %H:%M') setattr(datetime_cls, getter_name, Mock(return_value=datetime_obj)) self.add_patch( patch('dateparser.timezone_parser.datetime', new=datetime_cls))
class TestNoUseOtherPrivateToplevelVars(TestCase): """Check that private variables not set by us are not used.""" parameters = [param(m) for m in FUNCTIONS_SETTING_VARS] def test_pass_pub_var_used(self): """Check access/private_var passes if undefined public var is used.""" script = "message (${VALUE})\n" self.assertTrue( run_linter_throw(script, whitelist=["access/private_var"])) @parameterized.expand(parameters, testcase_func_doc=_PRIVATE_VAR_SET_FORMAT) def test_pass_variable_used(self, matcher): """Check access/private_var passes when priv var set by {}.""" # suppress(unnecessary-lambda,E731) xform = lambda x: "_{0}".format(x) private_var = matcher.find.generate(matcher.sub, lambda x: x, xform) script = ("{0} ({1})\n" "message ({2})\n").format(matcher.cmd, private_var, "${_VALUE}") self.assertTrue( run_linter_throw(script, whitelist=["access/private_var"])) def test_pass_priv_func_used(self): """Check access/private_var passes when using private func as var.""" script = ("function (_private_function)\n" "endfunction ()\n" "call (_private_function)\n") self.assertTrue( run_linter_throw(script, whitelist=["access/private_var"])) def test_pass_foreach_set(self): """Check access/private_var passes when private var set by foreach.""" script = ("foreach (_LOOP_VAR ${LIST})\n" " message (STATUS \"${_LOOP_VAR}\")\n" "endforeach ()\n") self.assertTrue( run_linter_throw(script, whitelist=["access/private_var"])) def test_fail_set_outside_scope(self): # suppress(no-self-use) """Check access/private_var fails when var set outside scope.""" script = ("foreach (_LOOP_VAR ${LIST})\n" "endforeach ()\n" "message (STATUS \"${_LOOP_VAR}\")\n") with ExpectedException(LinterFailure): run_linter_throw(script, whitelist=["access/private_var"]) def test_fail_priv_var_used(self): # suppress(no-self-use) """Check access/private_var fails on undefined private var used.""" script = "message (${_VALUE})\n" with ExpectedException(LinterFailure): run_linter_throw(script, whitelist=["access/private_var"])
class TestDateLocaleParser(BaseTestCase): def setUp(self): super(TestDateLocaleParser, self).setUp() @parameterized.expand([ param(date_obj={'date_obj': datetime(1999, 10, 1, 0, 0)}), param(date_obj={'period': 'day'}), param(date_obj={ 'date': datetime(2007, 1, 22, 0, 0), 'period': 'day' }), param(date_obj={'period': 'hour'}), param(date_obj=[datetime(2007, 1, 22, 0, 0), 'day']), param(date_obj={ 'date_obj': None, 'period': 'day' }), ]) def test_is_valid_date_obj(self, date_obj): self.given_parser(language=['en'], date_string='10 jan 2000', date_formats=None, settings=settings) self.when_date_object_is_validated(date_obj) self.then_date_object_is_invalid() def given_parser(self, language, date_string, date_formats, settings): self.parser = date._DateLocaleParser(language, date_string, date_formats, settings) def when_date_object_is_validated(self, date_obj): self.is_valid_date_obj = self.parser._is_valid_date_obj(date_obj) def then_date_object_is_invalid(self): self.assertFalse(self.is_valid_date_obj)
class TestTZPopping(BaseTestCase): def setUp(self): super(TestTZPopping, self).setUp() self.initial_string = self.datetime_string = self.timezone_offset = NotImplemented @parameterized.expand([ param('Sep 03 2014 | 4:32 pm EDT', -4), param('17th October, 2034 @ 01:08 am PDT', -7), param('October 17, 2014 at 7:30 am PST', -8), param('20 Oct 2014 13:08 CET', +1), param('15 May 2004', None), ]) def test_extracting_valid_offset(self, initial_string, expected_offset): self.given_string(initial_string) self.when_offset_popped_from_string() self.then_offset_is(expected_offset) @parameterized.expand([ param('Sep 03 2014 | 4:32 pm EDT', 'Sep 03 2014 | 4:32 pm'), param('17th October, 2034 @ 01:08 am PDT', '17th October, 2034 @ 01:08 am'), param('October 17, 2014 at 7:30 am PST', 'October 17, 2014 at 7:30 am'), param('20 Oct 2014 13:08 CET', '20 Oct 2014 13:08'), ]) def test_timezone_deleted_from_string(self, initial_string, result_string): self.given_string(initial_string) self.when_offset_popped_from_string() self.then_string_modified_to(result_string) def test_string_not_changed_if_no_timezone(self): self.given_string('15 May 2004') self.when_offset_popped_from_string() self.then_string_modified_to('15 May 2004') def given_string(self, string_): self.initial_string = string_ def when_offset_popped_from_string(self): self.datetime_string, self.timezone_offset = pop_tz_offset_from_string(self.initial_string) def then_string_modified_to(self, expected_string): self.assertEqual(expected_string, self.datetime_string) def then_offset_is(self, expected_offset): delta = timedelta(hours=expected_offset) if expected_offset is not None else None self.assertEqual(delta, self.timezone_offset)
class TestParser(BaseTestCase): @parameterized.expand([ param(date_string=u"april 2010"), param(date_string=u"11 March"), param(date_string=u"March"), param(date_string=u"31 2010"), param(date_string=u"31/2010"), ]) def test_error_is_raised_when_incomplete_dates_given(self, date_string): self.given_parser() self.given_settings(settings={'STRICT_PARSING': True}) self.then_error_is_raised_when_date_is_parsed(date_string) def given_parser(self): self.parser = _parser @apply_settings def given_settings(self, settings=None): self.settings = settings def then_error_is_raised_when_date_is_parsed(self, date_string): with self.assertRaises(ValueError): self.parser.parse(date_string, self.settings)
class TimeZoneSettingsTest(BaseTestCase): def setUp(self): super(TimeZoneSettingsTest, self).setUp() self.given_ds = NotImplemented self.result = NotImplemented self.timezone = NotImplemented self.confs = NotImplemented @parameterized.expand([ param('12 Feb 2015 10:30 PM +0100', datetime(2015, 2, 12, 21, 30)), param('12 Feb 2015 4:30 PM EST', datetime(2015, 2, 12, 21, 30)), param('12 Feb 2015 8:30 PM PKT', datetime(2015, 2, 12, 15, 30)), param('12 Feb 2015 8:30 PM ACT', datetime(2015, 2, 13, 1, 30)), ]) def test_should_return_tz_aware_dates(self, ds, dt): self.given(ds) self.given_configurations({'RETURN_AS_TIMEZONE_AWARE': True}) self.when_date_is_parsed() self.then_date_is_tz_aware() self.then_date_is(dt) @parameterized.expand([ param('12 Feb 2015 4:30 PM EST', datetime(2015, 2, 12, 16, 30), 'EST'), param('12 Feb 2015 8:30 PM PKT', datetime(2015, 2, 12, 20, 30), 'PKT'), param('12 Feb 2015 8:30 PM ACT', datetime(2015, 2, 12, 20, 30), 'ACT'), ]) def test_should_return_and_assert_tz(self, ds, dt, tz): self.given(ds) self.given_configurations({'RETURN_AS_TIMEZONE_AWARE': True, 'TIMEZONE': tz}) self.when_date_is_parsed() self.then_date_is_tz_aware() self.then_date_is(dt) self.then_timezone_is(tz) def then_timezone_is(self, tzname): self.assertEqual(self.result.tzinfo.tzname(''), tzname) def given(self, ds): self.given_ds = ds def given_configurations(self, confs): self.confs = confs def when_date_is_parsed(self): self.result = parse(self.given_ds, settings=(self.confs or {})) def then_date_is_tz_aware(self): self.assertIsInstance(self.result.tzinfo, tzinfo) def then_date_is(self, date): dtc = self.result.replace(tzinfo=None) self.assertEqual(dtc, date)
class TestParser(BaseTestCase): @parameterized.expand([ param(date_string=u"april 2010"), param(date_string=u"11 March"), param(date_string=u"March"), param(date_string=u"31 2010"), param(date_string=u"31/2010"), ]) def test_error_is_raised_when_incomplete_dates_given(self, date_string): self.given_parser() self.given_settings(settings={'STRICT_PARSING': True}) self.then_error_is_raised_when_date_is_parsed(date_string) @parameterized.expand([ param(date_string=u"Januar"), param(date_string=u"56341819"), param(date_string=u"56341819 Febr"), ]) def test_error_is_raised_when_invalid_dates_given_when_fuzzy(self, date_string): self.given_parser() self.given_settings(settings={'FUZZY': True}) self.when_date_is_parsed(date_string) self.then_error_was_raised(ValueError, ['Nothing date like found']) def given_parser(self): self.parser = _parser @apply_settings def given_settings(self, settings=None): self.settings = settings def when_date_is_parsed(self, date_string): try: self.parser.parse(date_string, self.settings) except Exception as error: self.error = error def then_error_is_raised_when_date_is_parsed(self, date_string): with self.assertRaises(ValueError): self.parser.parse(date_string, self.settings)
class TestUtils(BaseTestCase): def setUp(self): super(TestUtils, self).setUp() self.date_format = None self.result = None def given_date_format(self, date_format): self.date_format = date_format def when_date_seperator_is_parsed(self): self.result = find_date_separator(self.date_format) def then_date_seperator_is(self, sep): self.assertEqual(self.result, sep) @parameterized.expand([ param(date_format=fmt.format(sep=sep), expected_sep=sep) for (fmt, sep) in itertools.product(['%d{sep}%m{sep}%Y', '%d{sep}%m{sep}%Y %H:%M'], ['/', '.', '-', ':']) ]) def test_separator_extraction(self, date_format, expected_sep): self.given_date_format(date_format) self.when_date_seperator_is_parsed() self.then_date_seperator_is(expected_sep)
class TestColored(TestCase): def setUp(self): self.msg = 'message' @parameterized.expand([ param('red', '\x1b[31m'), param('green', '\x1b[32m'), param('cyan', '\x1b[36m'), param('white', '\x1b[37m'), param('yellow', '\x1b[33m'), param('underline', '\x1b[4m') ]) def test_various_decorations(self, decoration_name, ansi_prefix): expected = ansi_prefix + self.msg + "\x1b[0m" with_color = Colored() without_color = Colored(colorize=False) self.assertEquals(expected, getattr(with_color, decoration_name)(self.msg)) self.assertEquals(self.msg, getattr(without_color, decoration_name)(self.msg))
class TestValidateTime(BaseTestCase): def setUp(self): super(TestValidateTime, self).setUp() self.result = NotImplemented self.time_string = NotImplemented def when_date_is_given(self, time_string): self.time_string = time_string self.result = validate_time(time_string) def then_time_is_parsed_as(self, time): self.assertEqual(time, self.result) @parameterized.expand([ param(time_string='9 ساعت 10 دقیقه 30 ثانیه', time='9:10:30'), param(time_string='09 ساعت 10 دقیقه 30 ثانیه', time='09:10:30'), param(time_string='09 ساعت 0 دقیقه 0 ثانیه', time='09:0:0'), param(time_string='09 ساعت 00 دقیقه', time='09:00:00'), param(time_string='00 دقیقه', time='00:00:00'), param(time_string='15 دقیقه 30 ثانیه', time='00:15:30'), ]) def test_validate_time(self, time_string, time): self.when_date_is_given(time_string) self.then_time_is_parsed_as(time)
class GetIntersectingPeriodsTest(BaseTestCase): def test_date_arguments_and_date_range_with_default_post_days(self): low = datetime(2014, 6, 15) high = datetime(2014, 6, 16) dates = list(date.get_intersecting_periods(low, high)) self.assertEquals(1, len(dates)) self.assertEquals(low, dates[0]) @parameterized.expand([ param(low=datetime(2014, 4, 15), high=datetime(2014, 6, 25), expected_results=[ datetime(2014, 4, 1), datetime(2014, 5, 1), datetime(2014, 6, 1) ]), param(low=datetime(2014, 4, 25), high=datetime(2014, 5, 5), expected_results=[datetime(2014, 4, 1), datetime(2014, 5, 1)]), param(low=datetime(2014, 4, 5), high=datetime(2014, 4, 25), expected_results=[datetime(2014, 4, 1)]), param(low=datetime(2014, 4, 25), high=datetime(2014, 6, 5), expected_results=[ datetime(2014, 4, 1), datetime(2014, 5, 1), datetime(2014, 6, 1) ]), param(low=datetime(2014, 4, 25), high=datetime(2014, 4, 25), expected_results=[]), param(low=datetime(2014, 12, 31), high=datetime(2015, 1, 1), expected_results=[datetime(2014, 12, 1)]), ]) def test_should_one_date_for_each_month(self, low, high, expected_results): results = list(date.get_intersecting_periods(low, high, period='month')) self.assertEquals(expected_results, results) @parameterized.expand([ param(low=datetime(2014, 4, 15), high=datetime(2014, 5, 15), period='month', expected_results=[datetime(2014, 4, 1), datetime(2014, 5, 1)]), param(low=datetime(2014, 10, 30, 4, 30), high=datetime(2014, 11, 7, 5, 20), period='week', expected_results=[datetime(2014, 10, 27), datetime(2014, 11, 3)]), param(low=datetime(2014, 8, 13, 13, 21), high=datetime(2014, 8, 14, 14, 7), period='day', expected_results=[datetime(2014, 8, 13), datetime(2014, 8, 14)]), param(low=datetime(2014, 5, 11, 22, 4), high=datetime(2014, 5, 12, 0, 5), period='hour', expected_results=[ datetime(2014, 5, 11, 22, 0), datetime(2014, 5, 11, 23, 0), datetime(2014, 5, 12, 0, 0) ]), param(low=datetime(2014, 4, 25, 11, 11, 11), high=datetime(2014, 4, 25, 11, 12, 11), period='minute', expected_results=[ datetime(2014, 4, 25, 11, 11, 0), datetime(2014, 4, 25, 11, 12, 0) ]), param(low=datetime(2014, 12, 31, 23, 59, 58, 500), high=datetime(2014, 12, 31, 23, 59, 59, 600), period='second', expected_results=[ datetime(2014, 12, 31, 23, 59, 58, 0), datetime(2014, 12, 31, 23, 59, 59, 0) ]), ]) def test_periods(self, low, high, period, expected_results): results = list(date.get_intersecting_periods(low, high, period=period)) self.assertEquals(expected_results, results) @parameterized.expand([ 'years', 'months', 'days', 'hours', 'minutes', 'seconds', 'microseconds', 'some_period', ]) def test_should_reject_easily_mistaken_dateutil_arguments( self, invalid_period): low = datetime(2014, 6, 15) period = datetime(2014, 6, 25) with self.assertRaisesRegexp( ValueError, "Invalid period: {}".format(invalid_period)): date.get_intersecting_periods(low, period, period=invalid_period).next() @parameterized.expand([ param(low=datetime(2014, 4, 15), high=datetime(2014, 4, 14)), param(low=datetime(2014, 4, 25), high=datetime(2014, 4, 25)), ]) def test_empty_period(self, low, high): results = list(date.get_intersecting_periods(low, high, period='month')) self.assertEquals([], results)
class LinterFailure(Exception): """Exception raised when the linter reports a message.""" def __init__(self, message, repl): """Initialize exception with mesh and replacement.""" super(LinterFailure, self).__init__() self.message = message self.replacement = repl def __str__(self): """Represent as string.""" return str("{0}".format(self.message)) FormatStyle = namedtuple("FormatStyle", "start mid end") _KNOWN_STYLES = [ param(FormatStyle(start="#", mid="#", end="")), param(FormatStyle(start="rem", mid="rem", end="")), param(FormatStyle(start="//", mid="//", end="")), param(FormatStyle(start="/*", mid=" *", end=" */")) ] def style_format(script, style): """Format script for style, replace keys in script with comments.""" return script.format(s=style.start, m=style.mid, e=style.end) def run_linter_throw(relative_path, contents, style, **kwargs):
from nose.tools import assert_equal from nose_parameterized import parameterized, param def setup_module(): global app, db print('') print (__name__, 'setup_function()---') app = set_app() # db = set_db() # ----POSITIVE-------------------------- # картинка в соотвествии с требованиями #@allure.severity("high") @parameterized([param(media_json) for media_json in loads_from_json("media_positive.json")]) def test_add_media(media_json): media = media_json old_media = app.media.media_get_list() alert_message = app.media.media_add_one_file_browse(media) new_media = app.media.media_get_list() old_media.append(media) v1 = sorted(old_media, key=Media.id_or_max) v2 = sorted(new_media, key=Media.id_or_max) assert_equal(v1, v2, 'Элемент добавлен') alert_text = loads_from_json("alerts.json")['add_one_file'].message assert_equal(alert_message, alert_text, 'Сообщение об успешном добавлении файла отображается') # # картинка в соотвествии с требованиями через переименование # @parameterized([param(media_json) for media_json in load_from_json("media_positive_mod.json")])
return StringIO(text) def _from_filename(text, cleanup, mode="w", **kwargs): """Write a filename in a temporary directory.""" del kwargs tempdir = mkdtemp(dir=os.getcwd(), prefix="parseshebang_unit") cleanup(shutil.rmtree, tempdir) with open(os.path.join(tempdir, "script.py"), mode) as script: script.write(text) return script.name MODES = (param(Function(_from_fileobj, "from file object")), param(Function(_from_filename, "from file name"))) def _print_mode(func, num, params): """Format docstring for tests with extra flags if necessary.""" del num return func.__doc__[:-1] + """ with input {}.""".format(str(params[0][0])) class TestShebangParser(TestCase): """Unit test fixture for parse() function.""" def setUp(self):
os.utime(join(dest_target, 'dir4'), (mtime-1e-5, mtime-1e-5)) assert os.stat(join(dest_target, 'dir4')).st_mtime < mtime # Modification time of file3 so that the target is newer mtime = os.stat(join(dest_target, 'file3')).st_mtime os.utime(join(dest_target, 'file3'), (mtime+1e-5, mtime+1e-5)) assert os.stat(join(dest_target, 'file3')).st_mtime > mtime source_items = [join('target', i) for i in os.listdir(source_target)] dest_items = [join('target', i) for i in os.listdir(dest_target)] return source_items, dest_items @parameterized([ param(populate_dirs), ]) def test_match_directories(populate_fun): """A bit heavy test to check some copying and removing""" new_targets = [] archived = [] def backup_call(node): new_targets.append(node.item) def archive_call(node): archived.append(node.dest_item) with tempfile.TemporaryDirectory() as source_root, \ tempfile.TemporaryDirectory() as dest_root: source_items, dest_items = populate_fun(source_root, dest_root)
from algotrader.provider.broker.sim.simulator import Simulator from algotrader.provider.feed.pandas_memory import PandasMemoryDataFeed from algotrader.provider.subscription import BarSubscriptionType from algotrader.technical.ma import SMA from algotrader.trading.account import Account from algotrader.trading.order import Order from algotrader.trading.position import Position from algotrader.trading.ref_data import Instrument, Exchange, Currency from algotrader.utils.ser_deser import MsgPackSerializer, JsonSerializer, MapSerializer from algotrader.utils.time_series import DataSeries from algotrader.config.app import ApplicationConfig from algotrader.trading.context import ApplicationContext params = [ param('MsgPackSerializer', MsgPackSerializer), param('JsonSerializer', JsonSerializer), param('MapSerializer', MapSerializer) ] class SerializerTest(TestCase): # Market Data Event @parameterized.expand(params) def test_bar(self, name, serializer): item = Bar(open=18, high=19, low=17, close=17.5, vol=100, inst_id=1, timestamp=datetime.datetime.now()) SerializerTest.ser_deser(name, serializer, item) @parameterized.expand(params) def test_quote(self, name, serializer): item = Quote(bid=18, ask=19, bid_size=200, ask_size=500, inst_id=1, timestamp=datetime.datetime.now())
# -*- coding: utf-8 -*- from nose_parameterized import parameterized, param from model.project import Project from test import * import time def setup(): global app app = set_app() @parameterized([param(Project(**positive)) for positive in loads_from_json('project_create.json')['mheg_positive']]) def test_mheg_project_create_positive(mheg_positive): old_mheg_projects_list = app.project.get_mheg_projects_list() sleep(0.5) app.project.mheg_project_create_positive(mheg_positive) while not len(old_mheg_projects_list) + 1 == app.project.count_mheg_projects(): pass new_mheg_projects_list = app.project.get_mheg_projects_list() old_mheg_projects_list.append(mheg_positive) assert sorted(old_mheg_projects_list, key =(lambda x: x.branchName)) == sorted(new_mheg_projects_list,key = (lambda x: x.branchName)) @parameterized([param(Project(**empty_name)) for empty_name in loads_from_json('project_create.json')['mheg_empty_name']]) def test_mheg_project_create_negative_empty_name(mheg_empty_name): old_mheg_projects_list = app.project.get_mheg_projects_list() time.sleep(0.5) app.project.mheg_project_create_empty_name(mheg_empty_name) new_mheg_projects_list = app.project.get_mheg_projects_list() assert sorted(old_mheg_projects_list, key =(lambda x: x.branchName)) == sorted(new_mheg_projects_list,key = (lambda x: x.branchName))
app_config = ApplicationConfig(None, None, Clock.RealTime, persistence_config, provider_configs=[MongoDBConfig(dbname=name, create_at_start=create_at_start, delete_at_stop=mongo_delete_at_stop), CassandraConfig(contact_points=['127.0.0.1'], keyspace=name, create_at_start=create_at_start, delete_at_stop=cass_delete_at_stop), InMemoryStoreConfig(file="%s_db.p"%name, create_at_start=create_at_start, delete_at_stop=im_memory_delete_at_stop)]) context = ApplicationContext(app_config=app_config) clock = context.clock mongo = context.provider_mgr.get(DataStore.Mongo) cassandra = context.provider_mgr.get(DataStore.Cassandra) inmemory = context.provider_mgr.get(DataStore.InMemoryDB) params = [ param('Mongo', mongo), param('Cassandra', cassandra), param('InMemory', inmemory) ] class DataStoreTest(TestCase): @classmethod def setUpClass(cls): mongo.start(app_context=context) cassandra.start(app_context=context) inmemory.start(app_context=context) @classmethod def tearDownClass(cls): mongo.stop() cassandra.stop()
# -*- coding: utf-8 -*- from nose_parameterized import parameterized, param from model.project import Project from test import * import time def setup(): global app app = set_app() @parameterized([param(Project(**positive))for positive in loads_from_json('project_create.json')['stingray_positive']]) def test_create_stingray_project_positive(stingray_positive): old_stingray_projects_list = app.project.get_stingray_projects_list() time.sleep(0.5) app.project.stingray_project_create_positive(stingray_positive) while not len(old_stingray_projects_list) + 1 == app.project.count_stingray_projects(): pass new_stingray_projects_list = app.project.get_stingray_projects_list() old_stingray_projects_list.append(stingray_positive) assert sorted(old_stingray_projects_list, key =(lambda x: x.branchName)) == sorted(new_stingray_projects_list,key = (lambda x: x.branchName)) @parameterized([param(Project(**empty_name)) for empty_name in loads_from_json('project_create.json')['stingray_empty_name']]) def test_stingray_project_create_negative_empty_name(stingray_empty_name): old_stingray_projects_list = app.project.get_stingray_projects_list() time.sleep(0.5) app.project.stingray_project_create_empty_name(stingray_empty_name) new_stingray_projects_list = app.project.get_stingray_projects_list() assert sorted(old_stingray_projects_list, key =(lambda x: x.branchName)) == sorted(new_stingray_projects_list,key = (lambda x: x.branchName))
# -*- coding: utf-8 -*- from __future__ import print_function from config import * from model.media import Media from nose.tools import assert_equal from nose_parameterized import parameterized, param def setup_module(): global app, db print('') print (__name__, 'setup_function()---') app = set_app() # db = set_db() # POSITIVE @nose.allure.severity("small") @parameterized([param(media_json) for media_json in load_from_json("media_positive.json")]) def test_search_media_by_name(media_json): media = media_json old_media = app.media.media_get_results_of_search_by_text(media.name) new_media = app.media.media_search_by_name(media.name) v1 = sorted(old_media, key=Media.id_or_max) v2 = sorted(new_media, key=Media.id_or_max) assert_equal(v1, v2, 'Элемент найден')
import numpy as np from numpy import nan, arange import pandas STRING_SIM_ALGORITHMS = [ 'jaro', 'q_gram', 'cosine', 'jaro_winkler', 'dameraulevenshtein', 'levenshtein' ] NUMERIC_SIM_ALGORITHMS = [ 'step', 'linear', 'squared', 'exp', 'gauss' ] COMPARE_ALGORITHMS = [ # string param('string', 'given_name', 'given_name', method='jaro'), param('string', 'given_name', 'given_name', method='jarowinkler'), param('string', 'given_name', 'given_name', method='levenshtein'), param('string', 'given_name', 'given_name', method='damerau_levenshtein'), param('string', 'given_name', 'given_name', method='qgram'), param('string', 'given_name', 'given_name', method='cosine'), # numeric param('numeric', 'age', 'age', method='step', offset=3, origin=2), param('numeric', 'age', 'age', method='linear', offset=3, scale=3, origin=2), param('numeric', 'age', 'age', method='exp', offset=3, scale=3, origin=2), param('numeric', 'age', 'age', method='gauss', offset=3, scale=3, origin=2), param('numeric', 'age', 'age', method='squared', offset=3, scale=3, origin=2), # exact param('exact', 'given_name', 'given_name')
class TimeZoneSettingsTest(BaseTestCase): def setUp(self): super(TimeZoneSettingsTest, self).setUp() self.given_ds = NotImplemented self.result = NotImplemented self.timezone = NotImplemented self.confs = NotImplemented @parameterized.expand([ param('12 Feb 2015 10:30 PM +0100', datetime(2015, 2, 12, 22, 30), 'UTC\+01:00'), param('12 Feb 2015 4:30 PM EST', datetime(2015, 2, 12, 16, 30), 'EST'), param('12 Feb 2015 8:30 PM PKT', datetime(2015, 2, 12, 20, 30), 'PKT'), param('12 Feb 2015 8:30 PM ACT', datetime(2015, 2, 12, 20, 30), 'ACT'), ]) def test_should_return_and_assert_tz(self, ds, dt, tz): self.given(ds) self.given_configurations({}) self.when_date_is_parsed() self.then_date_is_tz_aware() self.then_date_is(dt) self.then_timezone_is(tz) @parameterized.expand([ param('12 Feb 2015 4:30 PM EST', datetime(2015, 2, 12, 16, 30), 'EST'), param('12 Feb 2015 8:30 PM PKT', datetime(2015, 2, 12, 20, 30), 'PKT'), param('12 Feb 2015 8:30 PM ACT', datetime(2015, 2, 12, 20, 30), 'ACT'), param('12 Feb 2015 8:30 PM', datetime(2015, 2, 12, 20, 30), ''), ]) def test_only_return_explicit_timezone(self, ds, dt, tz): self.given(ds) self.given_configurations({}) self.when_date_is_parsed() self.then_date_is(dt) if tz: self.then_date_is_tz_aware() self.then_timezone_is(tz) else: self.then_date_is_not_tz_aware() @parameterized.expand([ param( '12 Feb 2015 4:30 PM EST', datetime(2015, 2, 12, 16, 30), ), param( '12 Feb 2015 8:30 PM PKT', datetime(2015, 2, 12, 20, 30), ), param( '12 Feb 2015 8:30 PM ACT', datetime(2015, 2, 12, 20, 30), ), param( '12 Feb 2015 8:30 PM +0100', datetime(2015, 2, 12, 20, 30), ), ]) def test_should_return_naive_if_RETURN_AS_TIMEZONE_AWARE_IS_FALSE( self, ds, dt): self.given(ds) self.given_configurations({'RETURN_AS_TIMEZONE_AWARE': False}) self.when_date_is_parsed() self.then_date_is(dt) self.then_date_is_not_tz_aware() def then_timezone_is(self, tzname): self.assertEqual(self.result.tzinfo.tzname(''), tzname) def given(self, ds): self.given_ds = ds def given_configurations(self, confs): if 'TIMEZONE' not in confs: confs.update({'TIMEZONE': 'local'}) self.confs = settings.replace(**confs) def when_date_is_parsed(self): self.result = parse(self.given_ds, settings=(self.confs or {})) def then_date_is_tz_aware(self): self.assertIsInstance(self.result.tzinfo, tzinfo) def then_date_is_not_tz_aware(self): self.assertIsNone(self.result.tzinfo) def then_date_is(self, date): dtc = self.result.replace(tzinfo=None) self.assertEqual(dtc, date)
import unittest from nose_parameterized import parameterized, param @parameterized([param(2), param(3)]) def test_square(x): assert x**2 == x**2 class AddTestCase(unittest.TestCase): @parameterized.expand([ ("string1", "string1"), ("string2", "string2") ]) def test_check_string(self, _, s): assert isinstance(s, str)
class TestJalaliParser(BaseTestCase): def setUp(self): super(TestJalaliParser, self).setUp() self.result = NotImplemented self.date_string = NotImplemented self.parser = NotImplemented self.translated = NotImplemented def when_date_is_given(self, date_string): self.date_string = date_string self.parser = JalaliParser(date_string) self.result = self.parser.get_date() self.translated = self.parser.persian_to_latin(date_string) def then_month_is_parsed_as(self, month_name): self.assertEqual(month_name, self.translated) def then_weekday_is_parsed_as(self, weekday): self.assertEqual(weekday, self.translated) def then_digit_is_parsed_as(self, digit): self.assertEqual(digit, self.translated) def then_date_parsed_is(self, datetime): self.assertEqual(datetime, self.result) def then_numeral_parsed_is(self, datetime): self.assertEqual(datetime, self.translated) @parameterized.expand([ param(date_string='فروردین', latin='Farvardin'), param(date_string='اردیبهشت', latin='Ordibehesht'), param(date_string='خرداد', latin='Khordad'), param(date_string='تیر', latin='Tir'), param(date_string='مرداد', latin='Mordad'), param(date_string='شهریور', latin='Shahrivar'), param(date_string='مهر', latin='Mehr'), param(date_string='آبان', latin='Aban'), param(date_string='آذر', latin='Azar'), param(date_string='دی', latin='Dey'), param(date_string='بهمن', latin='Bahman'), param(date_string='اسفند', latin='Esfand'), ]) def test_replace_months(self, date_string, latin): self.when_date_is_given(date_string) self.then_month_is_parsed_as(latin) @parameterized.expand([ param(date_string='یکشنبه', latin='Sunday'), param(date_string='روز شنبه', latin='Saturday'), param(date_string='دوشنبه', latin='Monday'), param(date_string='سهشنبه', latin='Tuesday'), param(date_string='چهار شنبه', latin='Wednesday'), param(date_string='پنج شنبه', latin='Thursday'), param(date_string='جمعه', latin='Friday'), ]) def test_replace_weekdays(self, date_string, latin): self.when_date_is_given(date_string) self.then_weekday_is_parsed_as(latin) @parameterized.expand([ param(date_string='۰۱', latin='01'), param(date_string='۲۵', latin='25'), param(date_string='۶۷۴', latin='674'), param(date_string='۰۵۶۱۲۷۳۸۹۴', latin='0561273894') ]) def test_replace_digits(self, date_string, latin): self.when_date_is_given(date_string) self.then_digit_is_parsed_as(latin) @parameterized.expand([ param(persian='صفر', numeral='0'), param(persian='یک', numeral='1'), param(persian='اول', numeral='1'), param(persian='دو', numeral='2'), param(persian='دوم', numeral='2'), param(persian='سه', numeral='3'), param(persian='سوم', numeral='3'), param(persian='چهار', numeral='4'), param(persian='چهارم', numeral='4'), param(persian='پنج', numeral='5'), param(persian='پنجم', numeral='5'), param(persian='شش', numeral='6'), param(persian='ششم', numeral='6'), param(persian='هفت', numeral='7'), param(persian='هفتم', numeral='7'), param(persian='هشت', numeral='8'), param(persian='هشتمین', numeral='8'), param(persian='نه', numeral='9'), param(persian='نهم', numeral='9'), param(persian='ده', numeral='10'), param(persian='دهم', numeral='10'), param(persian='یازده', numeral='11'), param(persian='یازدهم', numeral='11'), param(persian='دوازده', numeral='12'), param(persian='دوازدهم', numeral='12'), param(persian='سیزده', numeral='13'), param(persian='سیزدهم', numeral='13'), param(persian='چهارده', numeral='14'), param(persian='چهاردهم', numeral='14'), param(persian='پانزده', numeral='15'), param(persian='پانزدهمین', numeral='15'), param(persian='شانزده', numeral='16'), param(persian='شانزدهم', numeral='16'), param(persian='هفده', numeral='17'), param(persian='هفدهم', numeral='17'), param(persian='هجده', numeral='18'), param(persian='هجدهم', numeral='18'), param(persian='نوزده', numeral='19'), param(persian='نوزدهم', numeral='19'), param(persian='بیست', numeral='20'), param(persian='بیستم', numeral='20'), param(persian='بیست و یک', numeral='21'), param(persian='بیست و دو', numeral='22'), param(persian='بیست ثانیه', numeral='22'), param(persian='بیست و سه', numeral='23'), param(persian='بیست و سوم', numeral='23'), param(persian='بیست و چهار', numeral='24'), param(persian='بیست و چهارم', numeral='24'), param(persian='بیست و پنج', numeral='25'), param(persian='بیست و شش', numeral='26'), param(persian='بیست و هفت', numeral='27'), param(persian='بیست و هفتمین', numeral='27'), param(persian='بیست و هشت', numeral='28'), param(persian='بیست و نه', numeral='29'), param(persian='سی', numeral='30'), param(persian='سی و یک', numeral='31'), param(persian='سی و یکم', numeral='31'), ]) def test_replace_day_literal_with_numerals(self, persian, numeral): self.when_date_is_given(persian) self.then_numeral_parsed_is(numeral) @parameterized.expand([ param(date_string=u'سه شنبه سوم شهریور ۱۳۹۴', dt=datetime(2015, 8, 25, 0, 0)), param(date_string=u'پنجشنبه چهارم تیر ۱۳۹۴', dt=datetime(2015, 6, 25, 0, 0)), param(date_string=u'شنبه یکم فروردین ۱۳۹۴', dt=datetime(2015, 3, 21, 0, 0)), param(date_string=u'یکشنبه شانزدهم آذر ۱۳۹۳', dt=datetime(2014, 12, 7, 0, 0)), param(date_string=u'دوشنبه دوازدهم آبان ۱۳۹۳', dt=datetime(2014, 11, 3, 0, 0)), param(date_string=u'یکشنبه سیزدهم مهر ۱۳۹۳', dt=datetime(2014, 10, 5, 0, 0)), param(date_string=u'دوشنبه دوم تیر ۱۳۹۳', dt=datetime(2014, 6, 23, 0, 0)), param(date_string=u'یکشنبه سوم فروردین ۱۳۹۳', dt=datetime(2014, 3, 23, 0, 0)), param(date_string=u'پنجشنبه دهم بهمن ۱۳۹۲', dt=datetime(2014, 1, 30, 0, 0)), param(date_string=u'شنبه چهاردهم دی ۱۳۹۲', dt=datetime(2014, 1, 4, 0, 0)), param(date_string=u'جمعه بیستم خرداد ۱۳۹۰', dt=datetime(2011, 6, 10, 0, 0)), param(date_string=u'شنبه نهم مرداد ۱۳۸۹', dt=datetime(2010, 7, 31, 0, 0)), param(date_string=u'پنجشنبه بیست و سوم اردیبهشت ۱۳۸۹', dt=datetime(2010, 5, 13, 0, 0)), param(date_string=u'جمعه سی ام اسفند ۱۳۸۷', dt=datetime(2009, 3, 20, 0, 0)), # dates with time component param(date_string=u'پنجشنبه ۲۶ شهريور ۱۳۹۴ ساعت ۹:۳۲', dt=datetime(2015, 9, 17, 9, 32)), param(date_string=u'دوشنبه ۲۳ شهريور ۱۳۹۴ ساعت ۱۹:۱۱', dt=datetime(2015, 9, 14, 19, 11)), param(date_string=u'جمعه سی ام اسفند ۱۳۸۷ساعت 19:47', dt=datetime(2009, 3, 20, 19, 47)), param(date_string=u'شنبه چهاردهم دی ۱۳۹۲ساعت 12:1', dt=datetime(2014, 1, 4, 12, 1)), param(date_string=u'پنجشنبه 26 شهریور 1394 ساعت ساعت 11 و 01 دقیقه و 47 ثانیه', dt=datetime(2015, 9, 17, 11, 1, 47)), param(date_string=u'پنجشنبه 26 شهریور 1394 ساعت ساعت 10 و 58 دقیقه و 04 ثانیه', dt=datetime(2015, 9, 17, 10, 58, 4)), param(date_string=u'سه شنبه 17 شهریور 1394 ساعت ساعت 18 و 21 دقیقه و 44 ثانیه', dt=datetime(2015, 9, 8, 18, 21, 44)), param(date_string=u'پنجشنبه 11 تیر 1394', dt=datetime(2015, 7, 2, 0, 0)), param(date_string=u'پنجشنبه 26 شهریور 1394 ساعت ساعت 11 و 01 دقیقه', dt=datetime(2015, 9, 17, 11, 1)), ]) def test_get_date(self, date_string, dt): self.when_date_is_given(date_string) self.then_date_parsed_is(dt)
@raises(TypeError) def test_truthtables_runner_invalid_type(): truthtables.runner(1) @raises(TypeError) def test_truthtables_invalid_type(): truthtables.TruthTable(1) @raises(TypeError) def test_truthtables_invalid_type_list(): truthtables.TruthTable([1]) @parameterized([ param([[True], [False]], 1), param([[True, True], [True, False], [False, True], [False, False]], 2), param([[True, True, True], [True, True, False], [True, False, True], [True, False, False], [False, True, True], [False, True, False], [False, False, True], [False, False, False]], 3) ]) def test_combinations(expected, num): actual = truthtables.get_combinations(num) assert_equal(expected, actual) if __name__ == "__main__": runmodule()