def test_generate(self): """ test generating url """ target = self._make_one() target.add('testing-route', 'a/{v1}') result = target.generate('testing-route', v1='b') compare(result, 'a/b')
def test_logging(self,l1,l2,l3): # we can now log as normal root.info('1') one.info('2') two.info('3') child.info('4') # and later check what was logged l1.check( ('root', 'INFO', '1'), ('one', 'INFO', '2'), ('two', 'INFO', '3'), ('one.child', 'INFO', '4'), ) l2.check( ('one', 'INFO', '2'), ('one.child', 'INFO', '4') ) l3.check( ('two', 'INFO', '3'), ('one.child', 'INFO', '4') ) # each logger also exposes the real # log records should anything else be neeeded compare(l3.records,[ C('logging.LogRecord'), C('logging.LogRecord'), ])
def test_get_game_from_score(self): """ You should be able to determine game from entry_id and score_category """ entry_2_id = TournamentEntry.query.filter_by( player_id='{}_player_{}'.format(self.tourn_1, 2), tournament_id=self.tourn_1).first().id entry_3_id = TournamentEntry.query.filter_by( player_id='{}_player_{}'.format(self.tourn_1, 3), tournament_id=self.tourn_1).first().id entry_4_id = TournamentEntry.query.filter_by( player_id='{}_player_{}'.format(self.tourn_1, 4), tournament_id=self.tourn_1).first().id # A regular player game = self.get_game_by_round(entry_4_id, 1) self.assertTrue(game is not None) game = self.get_game_by_round(entry_4_id, 1) entrants = [x.entrant_id for x in game.entrants.all()] compare(len(entrants), 2) self.assertTrue(entry_4_id in entrants) self.assertTrue(entry_2_id in entrants) # A player in a bye game = self.get_game_by_round(entry_3_id, 1) entrants = [x.entrant_id for x in game.entrants.all()] compare(len(entrants), 1) self.assertTrue(entry_3_id in entrants) # Poor data will return None rather than an error game = self.get_game_by_round(15, 1) self.assertTrue(game is None) game = self.get_game_by_round(1, 12) self.assertTrue(game is None)
def test_no___dict___not_strict_different(self): if py_34_plus: expected = ( "\n <C(failed):testfixtures.tests.test_com[42 chars] </C>" " != <X>", ) else: expected = ( "\n" " <C(failed):testfixtures.tests.test_comparison.X>\n" " x:1 != 2\n" " y:2 not in other\n" " </C> != <X>", ) x = X() x.x = 2 try: self.assertEqual( C(X, x=1, y=2, strict=False), x ) except AssertionError as e: compare(e.args, expected) else: self.fail('No exception raised!')
def test_cleanup_properly(self): r = Replacer() try: m = Mock() d = mkdtemp() m.return_value = d r.replace('testfixtures.tempdirectory.mkdtemp',m) self.failUnless(os.path.exists(d)) self.assertFalse(m.called) @tempdir() def test_method(d): d.write('something', b'stuff') d.check('something', ) self.assertFalse(m.called) compare(os.listdir(d),[]) test_method() self.assertTrue(m.called) self.failIf(os.path.exists(d)) finally: r.restore() if os.path.exists(d): # only runs if the test fails! rmtree(d) # pragma: no cover
def _compare_datadicts(self, original, output): ''' Compare a CKAN generated datadict to original datadict. Returns True if identical, otherwise throws an exception with useful output of differences. :param original: original datadict :param output: a datadict received from CKAN API ''' def convert_tags(tag_string): ''' Convert tag_string to tags dict. Copy-paste from ckan.tests.legacy.logic.test_tag_vocab.py. ''' key = 'vocab_tags' data = {key: tag_string} errors = [] context = {'model': model, 'session': model.Session} kata_tag_string_convert(key, data, errors, context) del data[key] return data data_dict = copy.deepcopy(original) # name (data pid), title and notes are generated so they shouldn't match data_dict.pop('name', None) data_dict.pop('title', None) data_dict.pop('notes', None) # lang* fields are converted to translation JSON strings and # after that they are not needed anymore data_dict.pop('langtitle', None) data_dict.pop('langnotes', None) # Terms of usage acceptance is checked but not saved data_dict.pop('accept-terms', None) # Create tags from original dataset's tag_string if not data_dict.get('tags'): data_dict['tags'] = df.unflatten(convert_tags(data_dict.get('tag_string'))).get('tags') data_dict.pop('tag_string', None) print data_dict['tags'] for tag_dict in output.get('tags'): # These are not provided from kata_tag_string_convert, so remove them tag_dict.pop('display_name') tag_dict.pop('id') tag_dict.pop('state') tag_dict.pop('vocabulary_id') # Remove xpaths because xpath-json converter not yet implemented data_dict.pop('xpaths', None) # Remove all values that are not present in the original data_dict output = dict((k, v) for k, v in output.items() if k in data_dict.keys()) # Take out automatically added distributor (CKAN user) output['agent'] = filter(lambda x: x.get('name') not in ['testsysadmin', 'tester'], output['agent']) testfixtures.compare(output, data_dict) return True
def test_sprocess_communicate_with_process(self): foo = ' foo' bar = ' bar' cmd = ["echo", "this is a command" + foo + bar] p = procopen(cmd, stdoutpipe=True) stdout, _ = p.communicate() compare(stdout, b"this is a command foo bar\n")
def test_gotcha_import_and_obtain(self): # Another gotcha is where people have locally obtained # a class attributes, where the normal patching doesn't # work: @replace('testfixtures.tests.sample1.date', test_date()) def test_something(): compare(sample1.str_today_2(), '2001-01-01') with ShouldRaise(AssertionError) as s: test_something() # This convoluted check is because we can't stub # out the date, since we're testing stubbing out # the date ;-) j, dt1, j, dt2, j = s.raised.args[0].split("'") # check we can parse the date dt1 = strptime(dt1, '%Y-%m-%d') # check the dt2 bit was as it should be compare(dt2, '2001-01-01') # What you need to do is replace the imported name: @replace('testfixtures.tests.sample1.today', test_date().today) def test_something(): compare(sample1.str_today_2(), '2001-01-01') test_something()
def test_language_tool_checker(self): target_file = os.path.join( here, 'languagetool_grammar.pdf') rez = language_tool_checker.main(target_file=target_file) compare(rez, [{'help': 'It would be a honour.', 'id': 'C2000', 'msg': 'misspelling - Use \'an\' instead of \'a\' if ' 'the following word starts with a vowel sound,' ' e.g. \'an article\', \'an hour\'', 'msg_name': 'EN_A_VS_AN', 'page': 'Slide 1'}, {'help': 'It would be a honour.', 'id': 'C2005', 'msg': 'misspelling - Possible spelling mistake found', 'msg_name': 'MORFOLOGIK_RULE_EN_US', 'page': 'Slide 1'}, {'help': 'It was only shown on ITV and ' 'not B.B.C.', 'id': 'C2005', 'msg': 'misspelling - Possible spelling mistake found', 'msg_name': 'MORFOLOGIK_RULE_EN_US', 'page': 'Slide 1'}, {'help': '... they\'re coats in the cloakroom. ' 'I know alot about precious stones. Have ' 'you seen th...', 'id': 'C2005', 'msg': 'misspelling - Possible spelling mistake found', 'msg_name': 'MORFOLOGIK_RULE_EN_US', 'page': 'Slide 3'}])
def _check(self,requirement,expected): result = _constrain( self.i, tuple(parse_requirements(requirement))[0] ) self.failUnless(isinstance(result,Requirement)) compare(expected,str(result))
def test_gotcha_import(self): # standard `replace` caveat, make sure you # patch all revelent places where date # has been imported: @replace('datetime.date', test_date()) def test_something(): from datetime import date compare(date.today(), d(2001, 1, 1)) compare(sample1.str_today_1(), '2001-01-02') with ShouldRaise(AssertionError) as s: test_something() # This convoluted check is because we can't stub # out the date, since we're testing stubbing out # the date ;-) j, dt1, j, dt2, j = s.raised.args[0].split("'") # check we can parse the date dt1 = strptime(dt1, '%Y-%m-%d') # check the dt2 bit was as it should be compare(dt2, '2001-01-02') # What you need to do is replace the imported type: @replace('testfixtures.tests.sample1.date', test_date()) def test_something(): compare(sample1.str_today_1(), '2001-01-01') test_something()
def test_load_local_requirements__with_blanks(self, mock_path_exists ): """ TestShakerMetadata::test_load_local_requirements: Test loading from local dependency file with blanks and comments """ # Setup mock_path_exists.return_value = True text_file_data = '\n'.join(["[email protected]:test_organisation/test1-formula.git==v1.0.1", "", "[email protected]:test_organisation/test2-formula.git==v2.0.1", " ", "#DONT_READ_ME", "[email protected]:test_organisation/test3-formula.git==v3.0.1"]) with patch('__builtin__.open', mock_open(read_data=()), create=True) as mopen: mopen.return_value.__iter__.return_value = text_file_data.splitlines() shaker.libs.logger.Logger().setLevel(logging.DEBUG) tempobj = ShakerMetadata(autoload=False) input_directory = '.' input_filename = 'test' tempobj.load_local_requirements(input_directory, input_filename) mock_path_exists.assert_called_once_with('./test') mopen.assert_called_once_with('./test', 'r') testfixtures.compare(tempobj.local_requirements, self._sample_dependencies)
def test_plugin_versions(self): self._write_jpi('test1', """ Url: http://wiki.jenkins-ci.org/display/JENKINS/Ant+Plugin Junk: 1.0 Extension-Name: test1 Implementation-Title: test1 Implementation-Version: 2 Plugin-Version: 2 """) self._write_jpi('test2', """ Junk: 1.0 Extension-Name: test2 Implementation-Title: test2 Implementation-Version: 1 Plugin-Version: 1 """) plugin = self.make_plugin() plugin.write_plugin_versions(self.dir.path, self.dir.path) compare( self.dir.read(self.dir.getpath('plugin-versions.txt')), expected=os.linesep.join(( 'test1: 2', 'test2: 1', '', )))
def test_gotcha_import(self): # standard `replace` caveat, make sure you # patch all revelent places where time # has been imported: @replace('time.time',test_time()) def test_something(): from time import time compare(time(),978307200.0) compare(sample1.str_time(),'978307201.0') s = should_raise(test_something,AssertionError) s() # This convoluted check is because we can't stub # out time, since we're testing stubbing out time ;-) j,t1,j,t2,j = s.raised.args[0].split("'") # check we can parse the time t1 = float(t1) # check the t2 bit was as it should be compare(t2,'978307201.0') # What you need to do is replace the imported type: @replace('testfixtures.tests.sample1.time',test_time()) def test_something(): compare(sample1.str_time(),'978307200.0') test_something()
def test_get_admin_resources(self): """Retrieve admin resources.""" url = reverse("api:resources-detail", args=[self.user.pk]) response = self.client.get(url) self.assertEqual(response.status_code, 200) expected = { "quota": 2, "mailboxes": 2, "domain_admins": 2, "domain_aliases": 2, "domains": 2, "mailbox_aliases": 2 } compare(expected, response.data) # As reseller => fails self.client.credentials( HTTP_AUTHORIZATION="Token {}".format(self.r_token.key)) response = self.client.get(url) self.assertEqual(response.status_code, 404) # As domain admin => fails self.client.credentials( HTTP_AUTHORIZATION="Token {}".format(self.da_token.key)) response = self.client.get(url) self.assertEqual(response.status_code, 404)
def test_mapping_with_top_level_merge(self): config = Config({'x': {'y': 1}}) data = {'z': 2} config.merge(data, mapping={ source: target.merge() }) compare(config.data, expected={'x': {'y': 1}, 'z': 2})
def test_stream_with_name_guess_parser(self): with NamedTemporaryFile(suffix='.json') as source: source.write(b'{"x": 1}') source.flush() source.seek(0) config = Config.from_stream(source) compare(config.x, expected=1)
def test_mapping_dotted_strings(self): config = Config({'a': {'b': 'old'}}) data = {'c': {'d': 'new'}} config.merge(data, mapping={ 'c.d': 'a.b' }) compare(config.data, expected={'a': {'b': 'new'}})
def test_mapping_type_conversion(self): config = Config({'x': 0}) data = {'y': '1'} config.merge(data, mapping={ convert(source['y'], int): target['x'] }) compare(config.data, expected={'x': 1})
def test_mapping_paths(self): config = Config({'x': 'old'}) data = {'foo': 'bar'} config.merge(data, mapping={ source['foo']: target['x'] }) compare(config.data, expected={'x': 'bar'})
def test_mapping_strings(self): config = Config({'x': 'old'}) data = {'foo': 'bar'} config.merge(data, mapping={ 'foo': 'x' }) compare(config.data, expected={'x': 'bar'})
def test_type_returns_new_object(self): config1 = Config((1, 2)) config2 = Config((3, 4)) def concat(context, source, target): return target + source config1.merge(config2, mergers={tuple: concat}) compare(config1.data, expected=(1, 2, 3, 4))
def test_nested_working(self): config1 = Config(dict(x=1, y=[2, 3], z=dict(a=4, b=5))) config2 = Config(dict(w=6, y=[7], z=dict(b=8, c=9))) config1.merge(config2) compare(config1.data, expected=dict(x=1, w=6, y=[2, 3, 7], z=dict(a=4, b=8, c=9)))
def test_set_rdsheet_trim(self): r = TestReader( ('Sheet1',[['X',' ']]), ('Sheet2',[['X','X']]), ) book = tuple(r.get_workbooks())[0][0] # fire methods on filter f = ColumnTrimmer() f.next = c = Mock() f.start() f.workbook(book,'new.xls') f.sheet(book.sheet_by_index(0),'new') f.row(0,0) f.cell(0,0,0,0) f.cell(0,1,0,1) f.set_rdsheet(book.sheet_by_index(1)) f.cell(0,0,1,0) f.cell(0,1,1,1) f.finish() compare(c.method_calls,[ ('start', (), {}), ('workbook', (C('xlutils.tests.fixtures.DummyBook'), 'new.xls'),{}), ('sheet', (C('xlrd.sheet.Sheet',name='Sheet1',strict=False), u'new'),{}), ('row', (0, 0),{}), ('cell', (0, 0, 0, 0),{}), ('cell', (0, 1, 0, 1),{}), ('set_rdsheet', (C('xlrd.sheet.Sheet',name='Sheet2',strict=False),),{}), ('cell', (0, 0, 1, 0),{}), ('cell', (0, 1, 1, 1),{}), ('finish', (), {}) ])
def test_use_write_sheet_name_in_logging(self,h): r = TestReader( ('Sheet1',[['X',' ']]), ) book = tuple(r.get_workbooks())[0][0] # fire methods on filter f = ColumnTrimmer() f.next = c = Mock() f.start() f.workbook(book,'new.xls') f.sheet(book.sheet_by_index(0),'new') f.row(0,0) f.cell(0,0,0,0) f.cell(0,1,0,1) f.finish() compare(c.method_calls,[ ('start', (), {}), ('workbook', (C('xlutils.tests.fixtures.DummyBook'), 'new.xls'),{}), ('sheet', (C('xlrd.sheet.Sheet',name='Sheet1',strict=False), u'new'),{}), ('row', (0, 0),{}), ('cell', (0, 0, 0, 0),{}), ('finish', (),{}) ]) h.check(( 'xlutils.filter', 'DEBUG', "Number of columns trimmed from 2 to 1 for sheet 'new'" ))
def test_custom_filepaths(self): # also tests the __call__ method class TestReader(BaseReader): def get_filepaths(self): return (test_xls_path,) t = TestReader() f = Mock() t(f) compare(f.method_calls,[ ('start',(),{}), ('workbook',(C('xlrd.Book', pickleable=0, formatting_info=1, on_demand=True, strict=False),'test.xls'),{}), ('sheet',(C('xlrd.sheet.Sheet'),u'Sheet1'),{}), ('row',(0,0),{}), ('cell',(0,0,0,0),{}), ('cell',(0,1,0,1),{}), ('row',(1,1),{}), ('cell',(1,0,1,0),{}), ('cell',(1,1,1,1),{}), ('sheet',(C('xlrd.sheet.Sheet'),u'Sheet2'),{}), ('row',(0,0),{}), ('cell',(0,0,0,0),{}), ('cell',(0,1,0,1),{}), ('row',(1,1),{}), ('cell',(1,0,1,0),{}), ('cell',(1,1,1,1),{}), ('finish',(),{}), ])
def test_start(self,d): f = ErrorFilter() f.next = m = Mock() f.wtbook = 'junk' f.handler.fired = 'junk' f.temp_path = d.path f.prefix = 'junk' j = open(os.path.join(d.path,'junk.xls'),'wb') j.write('junk') j.close() f.start() compare(f.wtbook,None) compare(f.handler.fired,False) self.failIf(os.path.exists(d.path)) compare(os.listdir(f.temp_path),[]) compare(f.prefix,0) f.finish() compare(m.method_calls,[ ('start', (), {}), ('finish', (), {}) ])
def test_override_type_mapping(self): config1 = Config([1, 2]) config2 = Config([3, 4]) def zipper(context, source, target): return zip(target, source) config1.merge(config2, mergers={list: zipper}) compare(config1.data, expected=[(1, 3), (2, 4)])
def test_multiple_workbooks_with_same_name(self,h): r = TestReader( ('Sheet1',[['S1R0C0']]), ) book = tuple(r.get_workbooks())[0][0] # fire methods on filter f = ErrorFilter() f.next = c = Mock() f.start() f.workbook(book,'new.xls') f.sheet(book.sheet_by_index(0),'new1') f.cell(0,0,0,0) f.workbook(book,'new.xls') f.sheet(book.sheet_by_index(0),'new2') f.cell(0,0,0,0) f.finish() compare(c.method_calls,[ ('start', (), {}), ('workbook', (C('xlrd.Book'), 'new.xls'),{}), ('sheet', (C('xlrd.sheet.Sheet',name='new1',strict=False), u'new1'),{}), ('row', (0, 0),{}), ('cell', (0, 0, 0, 0),{}), ('workbook', (C('xlrd.Book'), 'new.xls'),{}), ('sheet', (C('xlrd.sheet.Sheet',name='new2',strict=False), u'new2'),{}), ('row', (0, 0),{}), ('cell', (0, 0, 0, 0),{}), ('finish', (), {}) ]) self.assertEqual(len(h.records),0)
def test_supplement_type_mapping(self): config1 = Config({'x': (1, 2)}) config2 = Config({'x': (3, 4)}) def concat(context, source, target): return target + source config1.merge(config2, mergers=default_mergers+{tuple: concat}) compare(config1.data, expected={'x': (1, 2, 3, 4)})
def test_old_style_classes_same(self): class X: pass compare(X, X)
def test_string_same(self): compare('x', 'x')
def test_strict_okay(self): m = object() compare(m, m, strict=True)
def test_number_same(self): compare(1, 1)
def test_ignore_blank_lines(self): compare('\n a\n\n\t\nb\n ', ' a\nb', blanklines=False)
def test_ignore_trailing_whitespace(self): compare(' x \t\n', ' x\t \n', trailing_whitespace=False)
def test_show_whitespace_equal(self): compare('x', 'x', show_whitespace=True)
def test_tuple_and_list(self): compare((1, 2, 3), [1, 2, 3])
def test_object_same(self): o = object() compare(o, o)
def test_float_subclass_strict(self): class TestFloat(float): pass compare(TestFloat(0.75), TestFloat(0.75), strict=True)
def test_iterable_with_iterable_same(self): compare(xrange(1, 4), xrange(1, 4))
def test_generator_and_iterable(self): compare(generator(1, 2, 3), xrange(1, 4))
def test_sequence_and_generator(self): compare((1, 2, 3), generator(1, 2, 3))
def test_iterable_and_generator(self): compare(xrange(1, 4), generator(1, 2, 3))
def test_generator_same(self): compare(generator(1, 2, 3), generator(1, 2, 3))
def test_generator_and_sequence(self): compare(generator(1, 2, 3), (1, 2, 3))
def test_set_same(self): compare(set([1]), set([1]))
def test_nested_generator_tuple_right(self): compare(generator(1, 2, generator(3), 4), generator(1, 2, (3, ), 4))
def test_dict_same(self): compare(dict(x=1), dict(x=1))
def test_tuple_same(self): compare((1, 2, 3), (1, 2, 3))
def test_exception_different_object_c_wrapper(self): e1 = ValueError('some message') e2 = ValueError('some message') compare(C(e1), e2)
def test_dict_tuple_keys_same_value(self): compare({(1, 2): None}, {(1, 2): None})
def test_exception_same_object(self): e = ValueError('some message') compare(e, e)
def test_list_same(self): compare([1, 2, 3], [1, 2, 3])
def test_api_error_str_and_repr(self): error = WorkfrontAPIError('data', 503) compare(str(error), expected="503: 'data'") compare(repr(error), expected="WorkfrontAPIError('data', 503)")
def test_exception_same_c_wrapper(self): e1 = ValueError('some message') e2 = ValueError('some message') compare(C(e1), e2)
def test_load_multiple(self): self.server.add( url='/TEST', params='method=GET&id=xx,yy', response='{"data": [{"ID": "xx", "fieldOne": 1, "fieldTwo": 2}, ' '{"ID": "yy", "fieldOne": 3, "fieldTwo": 4}]}') results = self.session.load(self.api.TestObject, ['xx', 'yy']) compare(len(results), expected=2) obj = results[0] self.assertTrue(isinstance(obj, self.api.TestObject)) compare(obj.id, 'xx') compare(obj.field_one, 1) compare(obj.field_two, 2) obj = results[1] self.assertTrue(isinstance(obj, self.api.TestObject)) compare(obj.id, 'yy') compare(obj.field_one, 3) compare(obj.field_two, 4)
def test_read_mostly_py_rmd_file(rmd="""--- title: Simple file --- ```{python, echo=TRUE} import numpy as np x = np.arange(0, 2*math.pi, eps) ``` ```{python, echo=TRUE} x = np.arange(0,1,eps) y = np.abs(x)-.5 ``` ```{r} ls() ``` ```{r, results='asis', magic_args='-i x'} cat(stringi::stri_rand_lipsum(3), sep='\n\n') ``` """): nb = jupytext.reads(rmd, 'Rmd') assert nb.cells == [{ 'cell_type': 'raw', 'source': '---\ntitle: Simple file\n---', 'metadata': {} }, { 'cell_type': 'code', 'metadata': { 'hide_input': False }, 'execution_count': None, 'source': 'import numpy as np\n' 'x = np.arange(0, 2*math.pi, eps)', 'outputs': [] }, { 'cell_type': 'code', 'metadata': { 'hide_input': False }, 'execution_count': None, 'source': 'x = np.arange(0,1,eps)\ny = np.abs(x)-.5', 'outputs': [] }, { 'cell_type': 'code', 'metadata': {}, 'execution_count': None, 'source': '%%R\nls()', 'outputs': [] }, { 'cell_type': 'code', 'metadata': { 'results': "'asis'" }, 'execution_count': None, 'source': "%%R -i x\ncat(stringi::" "stri_rand_lipsum(3), sep='\n\n')", 'outputs': [] }] rmd2 = jupytext.writes(nb, 'Rmd') rmd2 = re.sub(r'```{r ', '```{r, ', rmd2) rmd2 = re.sub(r'```{python ', '```{python, ', rmd2) compare(rmd, rmd2)
def test_command_max_args(self): Popen = MockPopen() Popen.set_command('a command', 'out', 'err', 1, 345) process = Popen('a command', stdout=PIPE, stderr=PIPE) compare(process.pid, 345) compare(None, process.returncode) out, err = process.communicate() compare(out, 'out') compare(err, 'err') compare(process.returncode, 1) compare([ call.Popen('a command', stderr=-1, stdout=-1), call.Popen_instance.communicate() ], Popen.mock.method_calls)
def test_request(self): session = Session('test', url_template='http://127.0.0.1:8000') compare(session.request('GET', '/uri', {'foo': 'bar'}), expected='foo')