def test_refetching_unicode_names_searched_with_ascii(self): # searches with ascii names sometimes return non-ascii results # and we want to make sure that's not a problem for ascii_name, unicode_name in [ ("AEther Vial", u'Æther Vial'), ("Juzam Djinn", u'Juzám Djinn'), ("Jotun Grunt", u'Jötun Grunt') ]: # fetch self.assertEqual(Card.get(unicode_name).name, unicode_name) # re-fetch self.assertEqual(Card.get(ascii_name).name, unicode_name)
def test_who_what_when_where_why(self): wwwww = Card.get('Who/What/When/Where/Why') self.assertIsInstance(wwwww, Card) self.assertEqual(wwwww.name, 'Who/What/When/Where/Why') self.assertEqual(wwwww.colors, {'White', 'Blue', 'Black', 'Red', 'Green'})
def test_unicode_in_weird_spots(self): # weird unicode apostrophes from copying and pasting a cube list from # some random website for name, fixed_name in ((u'Moment\u2019s Peace', "Moment's Peace"), (u'Æther Adept', u'Æther Adept'), (u"Gideon’s Lawkeeper", "Gideon's Lawkeeper"), (u"Night’s Whisper", "Night's Whisper")): self.assertEqual(Card.get(name).name, fixed_name)
def _fix_pg_array_fields_in_serialized(serialized_card): card = None for field in ('_color_indicator', 'types', 'subtypes'): if isinstance(field, basestring): if card is None: card = Card.get(serialized_card['pk']) serialized_card['fields'][field] = getattr(card, field) return serialized_card
def handle(self, *args, **options): if not args: return if not os.path.exists(options['fixture_dir']): os.makedirs(options['fixture_dir']) def _fix_pg_array_fields_in_serialized(serialized_card): card = None for field in ('_color_indicator', 'types', 'subtypes'): if isinstance(field, basestring): if card is None: card = Card.get(serialized_card['pk']) serialized_card['fields'][field] = getattr(card, field) return serialized_card with open(options['outfile'], 'wb') as outfile: all_cards = {} cube = None for fpath in args: if not os.path.exists(fpath): raise CommandError('{} does not exist'.format(fpath)) cube = bulk_import.save_cube_from_file_path(fpath) all_cards.update(cube.as_dict()) base = os.path.basename(fpath).split('.')[0] outfile.write('{}_data = {};\n'.format( base, cube.serialize(cube.as_dict(), indent=4)) ) outfile.write('{}_data_array = {};\n'.format( base, cube.serialize(cube.as_list(), indent=4)) ) with open(os.path.join( options['fixture_dir'], '{}.json'.format(base) ), 'wb') as fixture_file: # hack, this can be done a lot better unfixed = json.loads(serializers.serialize( "json", cube.cards.all()) ) fixed = [_fix_pg_array_fields_in_serialized(card) for card in unfixed] json.dump(fixed, fixture_file) outfile.write('cuesbey_all_data = {};\n'.format( cube.serialize(all_cards, indent=4)) ) all_heuristics = [ v.as_dict() for v in Card.get_all_heuristics().itervalues() ] outfile.write('cuesbey_all_heuristics = {};\n'.format( cube.serialize(all_heuristics, indent=4)) )
def assertHeuristicsArePresent(self, name, expected_subset, keys_that_are_not_present=()): actual = Card.get(name).heuristics try: for k in keys_that_are_not_present: self.assertNotIn(k, actual) self.assertDictContainsSubset(expected_subset, actual) except AssertionError as e: raise AssertionError(e.message + ' problem with %s' % name)
def test_create_cards_given_names(self): for name, card_type in (('Zealous Conscripts', 'Creature'), ('Shelldock Isle', 'Land'), ('Sylvan Library', 'Enchantment')): fetched_card = Card.get(name) self.assertIsInstance(fetched_card, Card) self.assertIn(card_type, fetched_card.types) self.assertIn(fetched_card, Card.objects.all())
def available_heuristics(request): return HttpResponse( #TODO: consider how ths actually should be json.dumps([ dict(key=k, checked=v.checked) for k, v in Card.get_all_heuristics().iteritems() ]), mimetype="application/json" )
def assert_split_card_matches(self, search_name, name, colors): """ assert that the expectation matches for a given split card :param search_name: the string to search with :param name: the expected card name :param colors: the expected card colors :raise AssertionError: if the card doesn't match expectations """ fetched_card = Card.get(search_name) self.assertIsInstance(fetched_card, Card) self.assertEqual(name, fetched_card.name) self.assertEqual(colors, fetched_card.colors)
def card_contents(request): """ The expect contents of this request is = { 'card_names': ['card_name', 'card_name'*] # duplicates allowed } response = { 'cards': [{serialized card}, {serialized card}*], # duplicates allowed 'insert_job': 'job_id' # to get the results of async insert } """ if not request.is_ajax(): raise Http404 try: all_card_names = json.loads(request.body)['card_names'] except ValueError: raise ValueError("problem with %r" % request.body) fetched_cards, names_to_insert = retrieve_cards_from_names(all_card_names) response = { 'cards': {c.name: c.as_dict() for c in fetched_cards}, 'mismatches': Card.get_mismatched_names_map() } if names_to_insert: insert_job = async_get_cards.delay(names_to_insert, settings.REDIS_INFORMATION) response['insert_job'] = insert_job.id return HttpResponse( Cube.serialize(response), mimetype="application/json" )
def test_handle_null_color_indicator(self): self.assertEqual(set(), Card.get('Ghostfire').colors)
def test_handle_apostrophe_names(self): for name in ("Moment's Peace", "Sensei's Divining Top"): self.assertEqual(Card.get(name).name, name)
def test_fetching_unicode_names_with_ascii_text(self): self.assertEqual(Card.get("AEther Vial").name, u'Æther Vial') self.assertEqual(Card.get("Juzam Djinn").name, u'Juzám Djinn')
def test_getting_version_info(self): self.assertIn('60', Card.get('Demonic Tutor').versions) # split Cards take the left side self.assertIn('27165', Card.get('Fire//Ice').versions)
def test_parse_mana_cost(self): self.assertEqual(['5'], parse_mana_cost("{5}")) self.assertEqual(['5'], Card.get('Batterskull').parsed_mana_cost) self.assertEqual(['3', 'U/R', 'B'], Card.get('Slave of Bolas').parsed_mana_cost) self.assertEqual(['3', 'U/P'], Card.get('Phyrexian Metamorph').parsed_mana_cost)
def test_activated_abilities(self): self.assertEqual(['{1}{U}{B}'], Card.get('Creeping Tar Pit').activated_ability_mana_costs) self.assertEqual(['{W}', '{B}'], Card.get('Stormscape Apprentice').activated_ability_mana_costs) self.assertEqual(['{1}{G/P}'], Card.get('Birthing Pod').activated_ability_mana_costs) self.assertEqual(['{3}', '{U}'], Card.get('Crystal Shard').activated_ability_mana_costs)
def test_handle_color_indicator(self): self.assertEqual({'Blue'}, Card.get('Ancestral Vision').colors) self.assertEqual({'Green'}, Card.get('Dryad Arbor').colors) self.assertEqual({'White', 'Blue', 'Black', 'Red', 'Green'}, Card.get('Transguild Courier').colors)
def tearDown(self): """ needs to reset the caches of what's inserted and what's mismatched """ Card.reset_names_inserted()
from django.conf.urls import patterns, url, include from django.contrib import admin from cuesbey_main.cube_diff.views import (card_contents, poll_state, available_heuristics, blindly_return_cube_diff, get_diff, get_diff_link_id) from cuesbey_main.cube_diff.models import Card admin.autodiscover() # http://stackoverflow.com/questions/1797046/correct-place-to-put-extra-startup-code-in-django Card.reset_names_inserted() Card.make_standard_mismatches() urlpatterns = patterns('', url(r'^djangular/', include('djangular.urls')), url(r'^card_contents/?$', card_contents), url(r'^heuristics/?$', available_heuristics), url(r'^get_diff/(?P<link_id>[^/]+)/?$', get_diff), url(r'^get_diff_link/$', get_diff_link_id), url(r'^poll_state/$', poll_state, name="poll_state"), # FIXME: this is ugly and probably unnecessary url(r'^$', blindly_return_cube_diff), )