Esempio n. 1
0
class TestTeamHistoryDistrictsApiController(unittest2.TestCase):
    def setUp(self):
        app = webapp2.WSGIApplication([
            webapp2.Route(r'/<team_key:>',
                          ApiTeamHistoryDistrictsController,
                          methods=['GET'])
        ],
                                      debug=True)
        self.testapp = webtest.TestApp(app)

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache(
        )  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.team = Team(
            id="frc1124",
            name="UberBots",
            team_number=1124,
            nickname="UberBots",
        )

        self.district_team = DistrictTeam(id="2015ne_frc1124",
                                          team=self.team.key,
                                          year=2015,
                                          district_key=ndb.Key(
                                              District, '2015ne'))

        self.district = District(
            id='2015ne',
            year=2015,
        )

        self.team.put()
        self.district_team.put()
        self.district.put()

    def tearDown(self):
        self.testbed.deactivate()

    def testDistrictsApi(self):
        response = self.testapp.get(
            '/frc1124',
            headers={
                "X-TBA-App-Id":
                "tba-tests:team-history-districts-controller-test:v01"
            })
        district_dict = json.loads(response.body)

        self.assertTrue("2015" in district_dict)
        district_key = district_dict["2015"]

        self.assertEqual(district_key, "2015ne")
class TestTeamHistoryDistrictsApiController(unittest2.TestCase):
    def setUp(self):
        app = webapp2.WSGIApplication([webapp2.Route(r'/<team_key:>', ApiTeamHistoryDistrictsController, methods=['GET'])], debug=True)
        self.testapp = webtest.TestApp(app)

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.team = Team(
            id="frc1124",
            name="UberBots",
            team_number=1124,
            nickname="UberBots"
        )

        self.district_team = DistrictTeam(
            id="2015ne_frc1124",
            team=self.team.key,
            year=2015,
            district_key=ndb.Key(District, '2015ne')
        )

        self.district = District(
            id='2015ne',
            year=2015
        )

        self.team.put()
        self.district_team.put()
        self.district.put()

    def tearDown(self):
        self.testbed.deactivate()

    def testDistrictsApi(self):
        response = self.testapp.get('/frc1124', headers={"X-TBA-App-Id": "tba-tests:team-history-districts-controller-test:v01"})
        district_dict = json.loads(response.body)

        self.assertTrue("2015" in district_dict)
        district_key = district_dict["2015"]

        self.assertEqual(district_key, "2015ne")
class TestFIRSTElasticSearchEventListParser(unittest2.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.ne_district = District(
            id='2015ne',
            abbreviation='ne',
            year=2015,
            elasticsearch_name='NE FIRST'
        )
        self.ne_district.put()

    def tearDown(self):
        self.testbed.deactivate()

    def test_parse_event_list(self):
        with open('test_data/first_elasticsearch/2015_event_list.json', 'r') as f:
            events = FIRSTElasticSearchEventListParser(2015).parse(json.loads(f.read()))

            self.assertTrue(isinstance(events, list))

            self.assertEquals(len(events), 56 + 48 + 5)  # 56 regionals, 48 districts, 5 district championships

    def test_parse_regional_event(self):
        with open('test_data/first_elasticsearch/2015_event_list.json', 'r') as f:
            events = FIRSTElasticSearchEventListParser(2015).parse(json.loads(f.read()))

            for event in events:
                if event.key_name == '2015nyny':
                    self.assertEquals(event.key_name, "2015nyny")
                    self.assertEquals(event.name, "New York City Regional")
                    self.assertEquals(event.short_name, "New York City")
                    self.assertEquals(event.event_short, "nyny")
                    self.assertEquals(event.official, True)
                    self.assertEquals(event.start_date, datetime.datetime(year=2015, month=3, day=12, hour=0, minute=0, second=0))
                    self.assertEquals(event.end_date, datetime.datetime(year=2015, month=3, day=15, hour=23, minute=59, second=59))
                    self.assertEquals(event.venue, "Jacob K. Javits Convention Center")
                    self.assertEquals(event.city, "New York")
                    self.assertEquals(event.state_prov, "NY")
                    self.assertEquals(event.postalcode, "10001")
                    self.assertEquals(event.country, "USA")
                    self.assertEquals(event.venue_address, "Jacob K. Javits Convention Center\n655 West 34th Street\nNew York, NY 10001\nUSA")
                    self.assertEquals(event.year, 2015)
                    self.assertEquals(event.event_type_enum, EventType.REGIONAL)
                    self.assertEquals(event.district_key, None)
                    self.assertEquals(event.first_eid, '13339')
                    self.assertEquals(event.website, 'http://www.nycfirst.org')

    def test_parse_district_event(self):
        with open('test_data/first_elasticsearch/2015_event_list.json', 'r') as f:
            events = FIRSTElasticSearchEventListParser(2015).parse(json.loads(f.read()))
            for event in events:
                if event.key_name == '2015cthar':
                    self.assertEquals(event.key_name, "2015cthar")
                    self.assertEquals(event.name, "NE District - Hartford Event")
                    self.assertEquals(event.short_name, "Hartford")
                    self.assertEquals(event.event_short, "cthar")
                    self.assertEquals(event.official, True)
                    self.assertEquals(event.start_date, datetime.datetime(year=2015, month=3, day=27, hour=0, minute=0, second=0))
                    self.assertEquals(event.end_date, datetime.datetime(year=2015, month=3, day=29, hour=23, minute=59, second=59))
                    self.assertEquals(event.venue, "Hartford Public High School")
                    self.assertEquals(event.city, "Hartford")
                    self.assertEquals(event.state_prov, "CT")
                    self.assertEquals(event.postalcode, "06105")
                    self.assertEquals(event.country, "USA")
                    self.assertEquals(event.venue_address, "Hartford Public High School\n55 Forest Street\nHartford, CT 06105\nUSA")
                    self.assertEquals(event.year, 2015)
                    self.assertEquals(event.event_type_enum, EventType.DISTRICT)
                    self.assertEquals(event.district_key.id(), '2015ne')
                    self.assertEqual(event.district_key, self.ne_district.key)
                    self.assertEquals(event.first_eid, '13443')
                    self.assertEquals(event.website, 'http://www.nefirst.org/')

    def test_parse_district_cmp(self):
        with open('test_data/first_elasticsearch/2015_event_list.json', 'r') as f:
            events = FIRSTElasticSearchEventListParser(2015).parse(json.loads(f.read()))
            for event in events:
                if event.key_name == '2015necmp':
                    self.assertEquals(event.key_name, "2015necmp")
                    self.assertEquals(event.name, "NE FIRST District Championship presented by United Technologies")
                    self.assertEquals(event.short_name, "NE FIRST")
                    self.assertEquals(event.event_short, "necmp")
                    self.assertEquals(event.official, True)
                    self.assertEquals(event.start_date, datetime.datetime(year=2015, month=4, day=8, hour=0, minute=0, second=0))
                    self.assertEquals(event.end_date, datetime.datetime(year=2015, month=4, day=11, hour=23, minute=59, second=59))
                    self.assertEquals(event.venue, "Sports and Recreation Center, WPI")
                    self.assertEquals(event.city, "Worcester")
                    self.assertEquals(event.state_prov, "MA")
                    self.assertEquals(event.postalcode, "01609")
                    self.assertEquals(event.country, "USA")
                    self.assertEquals(event.venue_address, "Sports and Recreation Center, WPI\n100 Institute Road\nWorcester, MA 01609\nUSA")
                    self.assertEquals(event.year, 2015)
                    self.assertEquals(event.event_type_enum, EventType.DISTRICT_CMP)
                    self.assertEquals(event.district_key.id(), '2015ne')
                    self.assertEqual(event.district_key, self.ne_district.key)
                    self.assertEquals(event.first_eid, '13423')
                    self.assertEquals(event.website, 'http:///www.nefirst.org/')
class TestDistrictTeamsApiController(unittest2.TestCase):
    def setUp(self):
        app = webapp2.WSGIApplication([webapp2.Route(r'/<district_abbrev:>/<year:([0-9]*)>', ApiDistrictTeamsController, methods=['GET'])], debug=True)
        self.testapp = webtest.TestApp(app)

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.team = Team(
            id="frc281",
            name="Michelin / Caterpillar / Greenville Technical College /\
            jcpenney / Baldor / ASME / Gastroenterology Associates /\
            Laserflex South & Greenville County Schools & Greenville\
            Technical Charter High School",
            team_number=281,
            nickname="EnTech GreenVillians",
            city="Greenville",
            state_prov="SC",
            country="USA",
            website="www.entech.org",
            motto="Infiltrating Young Minds One Robot at a Time"
        )

        self.district = District(
            id='2015ne',
            year=2015,
            abbreviation='ne'
        )

        self.district_team = DistrictTeam(
            id="2015ne_frc281",
            team=self.team.key,
            year=2015,
            district_key=ndb.Key(District, '2015ne')
        )

        self.team.put()
        self.district.put()
        self.district_team.put()

    def tearDown(self):
        self.testbed.deactivate()

    def assertTeamJson(self, team):
        team = team[0]
        self.assertEqual(team["key"], self.team.key_name)
        self.assertEqual(team["team_number"], self.team.team_number)
        self.assertEqual(team["nickname"], self.team.nickname)
        self.assertEqual(team["location"], self.team.location)
        self.assertEqual(team["locality"], "Greenville")
        self.assertEqual(team["country_name"], "USA")
        self.assertEqual(team["region"], "SC")
        self.assertEqual(team["website"], self.team.website)
        self.assertEqual(team["motto"], None)

    def test_districts_api(self):
        response = self.testapp.get('/ne/2015', headers={"X-TBA-App-Id": "tba-tests:team-districts-controller-test:v01"})
        teams = json.loads(response.body)
        self.assertTeamJson(teams)
Esempio n. 5
0
class TestDistrictTeamsApiController(unittest2.TestCase):
    def setUp(self):
        app = webapp2.WSGIApplication([
            webapp2.Route(r'/<district_abbrev:>/<year:([0-9]*)>',
                          ApiDistrictTeamsController,
                          methods=['GET'])
        ],
                                      debug=True)
        self.testapp = webtest.TestApp(app)

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache(
        )  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.team = Team(
            id="frc281",
            name="Michelin / Caterpillar / Greenville Technical College /\
            jcpenney / Baldor / ASME / Gastroenterology Associates /\
            Laserflex South & Greenville County Schools & Greenville\
            Technical Charter High School",
            team_number=281,
            nickname="EnTech GreenVillians",
            city="Greenville",
            state_prov="SC",
            country="USA",
            website="www.entech.org",
            motto="Infiltrating Young Minds One Robot at a Time")

        self.district = District(id='2015ne', year=2015, abbreviation='ne')

        self.district_team = DistrictTeam(id="2015ne_frc281",
                                          team=self.team.key,
                                          year=2015,
                                          district_key=ndb.Key(
                                              District, '2015ne'))

        self.team.put()
        self.district.put()
        self.district_team.put()

    def tearDown(self):
        self.testbed.deactivate()

    def assertTeamJson(self, team):
        team = team[0]
        self.assertEqual(team["key"], self.team.key_name)
        self.assertEqual(team["team_number"], self.team.team_number)
        self.assertEqual(team["nickname"], self.team.nickname)
        self.assertEqual(team["location"], self.team.location)
        self.assertEqual(team["locality"], "Greenville")
        self.assertEqual(team["country_name"], "USA")
        self.assertEqual(team["region"], "SC")
        self.assertEqual(team["website"], self.team.website)
        self.assertEqual(team["motto"], None)

    def test_districts_api(self):
        response = self.testapp.get(
            '/ne/2015',
            headers={
                "X-TBA-App-Id": "tba-tests:team-districts-controller-test:v01"
            })
        teams = json.loads(response.body)
        self.assertTeamJson(teams)
class TestDatabaseCacheClearer(unittest2.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.eventteam_2015casj_frc254 = EventTeam(
            id='2015casj_frc254',
            event=ndb.Key(Event, '2015casj'),
            team=ndb.Key(Team, 'frc254'),
            year=2015,
        )

        self.eventteam_2015cama_frc604 = EventTeam(
            id='2015cama_frc604',
            event=ndb.Key(Event, '2015cama'),
            team=ndb.Key(Team, 'frc604'),
            year=2015,
        )

        self.eventteam_2010cama_frc604 = EventTeam(
            id='2010cama_frc604',
            event=ndb.Key(Event, '2010cama'),
            team=ndb.Key(Team, 'frc604'),
            year=2010,
        )

        self.eventteam_2016necmp_frc125 = EventTeam(
            id='2016necmp_frc125',
            event=ndb.Key(Event, '2016necmp'),
            team=ndb.Key(Team, 'frc125'),
            year=2016,
        )

        self.eventteam_2015casj_frc254.put()
        self.eventteam_2015cama_frc604.put()
        self.eventteam_2010cama_frc604.put()
        self.eventteam_2016necmp_frc125.put()

        self.districtteam_2015fim_frc254 = DistrictTeam(
            id='2015fim_frc254',
            district_key=ndb.Key(District, '2015fim'),
            team=ndb.Key(Team, 'frc254'),
            year=2015,
        )

        self.districtteam_2015mar_frc604 = DistrictTeam(
            id='2015mar_frc604',
            district_key=ndb.Key(District, '2015mar'),
            team=ndb.Key(Team, 'frc604'),
            year=2015,
        )

        self.districtteam_2016ne_frc604 = DistrictTeam(
            id='2016ne_frc604',
            district_key=ndb.Key(District, '2016ne'),
            team=ndb.Key(Team, 'frc604'),
            year=2016,
        )

        self.districtteam_2015fim_frc254.put()
        self.districtteam_2015mar_frc604.put()
        self.districtteam_2016ne_frc604.put()

        self.district_2015ne = District(
            id='2015ne',
            year=2015,
            abbreviation='ne',
        )

        self.district_2016chs = District(
            id='2016chs',
            year=2016,
            abbreviation='chs',
        )
        self.district_2015ne.put()
        self.district_2016chs.put()

        self.event_2016necmp = Event(
            id='2016necmp',
            year=2016,
            district_key=ndb.Key(District, '2016ne'),
            event_short='necmp',
            event_type_enum=EventType.DISTRICT_CMP,
        )
        self.event_2016necmp.put()

    def tearDown(self):
        self.testbed.deactivate()

    def test_award_updated(self):
        affected_refs = {
            'event': {ndb.Key(Event, '2015casj'), ndb.Key(Event, '2015cama')},
            'team_list': {ndb.Key(Team, 'frc254'), ndb.Key(Team, 'frc604')},
            'year': {2014, 2015}
        }
        cache_keys = [q.cache_key for q in get_affected_queries.award_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 12)
        self.assertTrue(EventAwardsQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventAwardsQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(TeamAwardsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamAwardsQuery('frc604').cache_key in cache_keys)
        self.assertTrue(TeamYearAwardsQuery('frc254', 2014).cache_key in cache_keys)
        self.assertTrue(TeamYearAwardsQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(TeamYearAwardsQuery('frc604', 2014).cache_key in cache_keys)
        self.assertTrue(TeamYearAwardsQuery('frc604', 2015).cache_key in cache_keys)
        self.assertTrue(TeamEventAwardsQuery('frc254', '2015casj').cache_key in cache_keys)
        self.assertTrue(TeamEventAwardsQuery('frc254', '2015cama').cache_key in cache_keys)
        self.assertTrue(TeamEventAwardsQuery('frc604', '2015casj').cache_key in cache_keys)
        self.assertTrue(TeamEventAwardsQuery('frc604', '2015cama').cache_key in cache_keys)

    def test_event_updated(self):
        affected_refs = {
            'key': {ndb.Key(Event, '2015casj'), ndb.Key(Event, '2015cama')},
            'year': {2014, 2015},
            'district_key': {ndb.Key(District, '2015fim'), ndb.Key(District, '2014mar')}
        }
        cache_keys = [q.cache_key for q in get_affected_queries.event_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 10)
        self.assertTrue(EventQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(EventListQuery(2014).cache_key in cache_keys)
        self.assertTrue(EventListQuery(2015).cache_key in cache_keys)
        self.assertTrue(DistrictEventsQuery('2015fim').cache_key in cache_keys)
        self.assertTrue(DistrictEventsQuery('2014mar').cache_key in cache_keys)
        self.assertTrue(TeamEventsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamEventsQuery('frc604').cache_key in cache_keys)
        self.assertTrue(TeamYearEventsQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(TeamYearEventsQuery('frc604', 2015).cache_key in cache_keys)

    def test_event_details_updated(self):
        affected_refs = {
            'key': {ndb.Key(EventDetails, '2015casj'), ndb.Key(EventDetails, '2015cama')},
        }
        cache_keys = [q.cache_key for q in get_affected_queries.event_details_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 2)
        self.assertTrue(EventDetailsQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventDetailsQuery('2015cama').cache_key in cache_keys)

    def test_match_updated(self):
        affected_refs = {
            'key': {ndb.Key(Match, '2015casj_qm1'), ndb.Key(Match, '2015casj_qm2')},
            'event': {ndb.Key(Event, '2015casj'), ndb.Key(Event, '2015cama')},
            'team_keys': {ndb.Key(Team, 'frc254'), ndb.Key(Team, 'frc604')},
            'year': {2014, 2015},
        }
        cache_keys = [q.cache_key for q in get_affected_queries.match_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 12)
        self.assertTrue(MatchQuery('2015casj_qm1').cache_key in cache_keys)
        self.assertTrue(MatchQuery('2015casj_qm2').cache_key in cache_keys)
        self.assertTrue(EventMatchesQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventMatchesQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(TeamEventMatchesQuery('frc254', '2015casj').cache_key in cache_keys)
        self.assertTrue(TeamEventMatchesQuery('frc254', '2015cama').cache_key in cache_keys)
        self.assertTrue(TeamEventMatchesQuery('frc604', '2015casj').cache_key in cache_keys)
        self.assertTrue(TeamEventMatchesQuery('frc604', '2015cama').cache_key in cache_keys)
        self.assertTrue(TeamYearMatchesQuery('frc254', 2014).cache_key in cache_keys)
        self.assertTrue(TeamYearMatchesQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(TeamYearMatchesQuery('frc604', 2014).cache_key in cache_keys)
        self.assertTrue(TeamYearMatchesQuery('frc604', 2015).cache_key in cache_keys)

    def test_media_updated_team(self):
        affected_refs = {
            'references': {ndb.Key(Team, 'frc254'), ndb.Key(Team, 'frc604')},
            'year': {2014, 2015},
        }
        cache_keys = [q.cache_key for q in get_affected_queries.media_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 10)
        self.assertTrue(TeamYearMediaQuery('frc254', 2014).cache_key in cache_keys)
        self.assertTrue(TeamYearMediaQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(TeamSocialMediaQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamYearMediaQuery('frc604', 2014).cache_key in cache_keys)
        self.assertTrue(TeamYearMediaQuery('frc604', 2015).cache_key in cache_keys)
        self.assertTrue(TeamSocialMediaQuery('frc604').cache_key in cache_keys)
        self.assertTrue(EventTeamsMediasQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(EventTeamsMediasQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventTeamsPreferredMediasQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(EventTeamsPreferredMediasQuery('2015casj').cache_key in cache_keys)

    def test_media_updated_event(self):
        affected_refs = {
            'references': {ndb.Key(Event, '2016necmp')},
            'year': {2016},
        }
        cache_keys = [q.cache_key for q in get_affected_queries.media_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 1)
        self.assertTrue(EventMediasQuery('2016necmp').cache_key in cache_keys)

    def test_robot_updated(self):
        affected_refs = {
            'team': {ndb.Key(Team, 'frc254'), ndb.Key(Team, 'frc604')},
        }
        cache_keys = [q.cache_key for q in get_affected_queries.robot_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 2)
        self.assertTrue(TeamRobotsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamRobotsQuery('frc604').cache_key in cache_keys)

    def test_team_updated(self):
        affected_refs = {
            'key': {ndb.Key(Team, 'frc254'), ndb.Key(Team, 'frc604')},
        }
        cache_keys = [q.cache_key for q in get_affected_queries.team_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 13)
        self.assertTrue(TeamQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamQuery('frc604').cache_key in cache_keys)
        self.assertTrue(TeamListQuery(0).cache_key in cache_keys)
        self.assertTrue(TeamListQuery(1).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2015, 0).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2015, 1).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2010, 1).cache_key in cache_keys)
        self.assertTrue(DistrictTeamsQuery('2015fim').cache_key in cache_keys)
        self.assertTrue(DistrictTeamsQuery('2015mar').cache_key in cache_keys)
        self.assertTrue(DistrictTeamsQuery('2016ne').cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2010cama').cache_key in cache_keys)

    def test_eventteam_updated(self):
        affected_refs = {
            'event': {ndb.Key(Event, '2015casj'), ndb.Key(Event, '2015cama')},
            'team': {ndb.Key(Team, 'frc254'), ndb.Key(Team, 'frc604')},
            'year': {2014, 2015}
        }
        cache_keys = [q.cache_key for q in get_affected_queries.eventteam_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 18)
        self.assertTrue(TeamEventsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamEventsQuery('frc604').cache_key in cache_keys)
        self.assertTrue(TeamParticipationQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamParticipationQuery('frc604').cache_key in cache_keys)
        self.assertTrue(TeamYearEventsQuery('frc254', 2014).cache_key in cache_keys)
        self.assertTrue(TeamYearEventsQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(TeamYearEventsQuery('frc604', 2014).cache_key in cache_keys)
        self.assertTrue(TeamYearEventsQuery('frc604', 2015).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2014, 0).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2014, 1).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2015, 0).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2015, 1).cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(EventTeamsMediasQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(EventTeamsMediasQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventTeamsPreferredMediasQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(EventTeamsPreferredMediasQuery('2015casj').cache_key in cache_keys)

    def test_districtteam_updated(self):
        affected_refs = {
            'district_key': {ndb.Key(District, '2015fim'), ndb.Key(District, '2015mar')},
            'team': {ndb.Key(Team, 'frc254'), ndb.Key(Team, 'frc604')}
        }
        cache_keys = [q.cache_key for q in get_affected_queries.districtteam_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 4)
        self.assertTrue(DistrictTeamsQuery('2015fim').cache_key in cache_keys)
        self.assertTrue(DistrictTeamsQuery('2015mar').cache_key in cache_keys)
        self.assertTrue(TeamDistrictsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamDistrictsQuery('frc604').cache_key in cache_keys)

    def test_district_updated(self):
        affected_refs = {
            'key': {ndb.Key(District, '2016ne')},
            'year': {2015, 2016},
            'abbreviation': {'ne', 'chs'}
        }
        cache_keys = [q.cache_key for q in get_affected_queries.district_updated(affected_refs)]

        self.assertEqual(len(cache_keys), 11)
        self.assertTrue(DistrictsInYearQuery(2015).cache_key in cache_keys)
        self.assertTrue(DistrictsInYearQuery(2016).cache_key in cache_keys)
        self.assertTrue(DistrictHistoryQuery('ne').cache_key in cache_keys)
        self.assertTrue(DistrictHistoryQuery('chs').cache_key in cache_keys)
        self.assertTrue(DistrictQuery('2016ne').cache_key in cache_keys)
        self.assertTrue(TeamDistrictsQuery('frc604').cache_key in cache_keys)

        # Necessary because APIv3 Event models include the District model
        self.assertTrue(EventQuery('2016necmp').cache_key in cache_keys)
        self.assertTrue(EventListQuery(2016).cache_key in cache_keys)
        self.assertTrue(DistrictEventsQuery('2016ne').cache_key in cache_keys)
        self.assertTrue(TeamEventsQuery('frc125').cache_key in cache_keys)
        self.assertTrue(TeamYearEventsQuery('frc125', 2016).cache_key in cache_keys)
class TestDatabaseCacheClearer(unittest2.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache(
        )  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.eventteam_2015casj_frc254 = EventTeam(
            id='2015casj_frc254',
            event=ndb.Key(Event, '2015casj'),
            team=ndb.Key(Team, 'frc254'),
            year=2015,
        )

        self.eventteam_2015cama_frc604 = EventTeam(
            id='2015cama_frc604',
            event=ndb.Key(Event, '2015cama'),
            team=ndb.Key(Team, 'frc604'),
            year=2015,
        )

        self.eventteam_2010cama_frc604 = EventTeam(
            id='2010cama_frc604',
            event=ndb.Key(Event, '2010cama'),
            team=ndb.Key(Team, 'frc604'),
            year=2010,
        )

        self.eventteam_2016necmp_frc125 = EventTeam(
            id='2016necmp_frc125',
            event=ndb.Key(Event, '2016necmp'),
            team=ndb.Key(Team, 'frc125'),
            year=2016,
        )

        self.eventteam_2015casj_frc254.put()
        self.eventteam_2015cama_frc604.put()
        self.eventteam_2010cama_frc604.put()
        self.eventteam_2016necmp_frc125.put()

        self.districtteam_2015fim_frc254 = DistrictTeam(
            id='2015fim_frc254',
            district_key=ndb.Key(District, '2015fim'),
            team=ndb.Key(Team, 'frc254'),
            year=2015,
        )

        self.districtteam_2015mar_frc604 = DistrictTeam(
            id='2015mar_frc604',
            district_key=ndb.Key(District, '2015mar'),
            team=ndb.Key(Team, 'frc604'),
            year=2015,
        )

        self.districtteam_2016ne_frc604 = DistrictTeam(
            id='2016ne_frc604',
            district_key=ndb.Key(District, '2016ne'),
            team=ndb.Key(Team, 'frc604'),
            year=2016,
        )

        self.districtteam_2015fim_frc254.put()
        self.districtteam_2015mar_frc604.put()
        self.districtteam_2016ne_frc604.put()

        self.district_2015ne = District(
            id='2015ne',
            year=2015,
            abbreviation='ne',
        )

        self.district_2016chs = District(
            id='2016chs',
            year=2016,
            abbreviation='chs',
        )
        self.district_2015ne.put()
        self.district_2016chs.put()

        self.event_2016necmp = Event(
            id='2016necmp',
            year=2016,
            district_key=ndb.Key(District, '2016ne'),
            event_short='necmp',
            event_type_enum=EventType.DISTRICT_CMP,
        )
        self.event_2016necmp.put()

    def tearDown(self):
        self.testbed.deactivate()

    def test_award_updated(self):
        affected_refs = {
            'event': {ndb.Key(Event, '2015casj'),
                      ndb.Key(Event, '2015cama')},
            'team_list': {ndb.Key(Team, 'frc254'),
                          ndb.Key(Team, 'frc604')},
            'year': {2014, 2015}
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.award_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 12)
        self.assertTrue(EventAwardsQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventAwardsQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(TeamAwardsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamAwardsQuery('frc604').cache_key in cache_keys)
        self.assertTrue(
            TeamYearAwardsQuery('frc254', 2014).cache_key in cache_keys)
        self.assertTrue(
            TeamYearAwardsQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(
            TeamYearAwardsQuery('frc604', 2014).cache_key in cache_keys)
        self.assertTrue(
            TeamYearAwardsQuery('frc604', 2015).cache_key in cache_keys)
        self.assertTrue(
            TeamEventAwardsQuery('frc254', '2015casj').cache_key in cache_keys)
        self.assertTrue(
            TeamEventAwardsQuery('frc254', '2015cama').cache_key in cache_keys)
        self.assertTrue(
            TeamEventAwardsQuery('frc604', '2015casj').cache_key in cache_keys)
        self.assertTrue(
            TeamEventAwardsQuery('frc604', '2015cama').cache_key in cache_keys)

    def test_event_updated(self):
        affected_refs = {
            'key': {ndb.Key(Event, '2015casj'),
                    ndb.Key(Event, '2015cama')},
            'year': {2014, 2015},
            'district_key':
            {ndb.Key(District, '2015fim'),
             ndb.Key(District, '2014mar')}
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.event_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 10)
        self.assertTrue(EventQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(EventListQuery(2014).cache_key in cache_keys)
        self.assertTrue(EventListQuery(2015).cache_key in cache_keys)
        self.assertTrue(DistrictEventsQuery('2015fim').cache_key in cache_keys)
        self.assertTrue(DistrictEventsQuery('2014mar').cache_key in cache_keys)
        self.assertTrue(TeamEventsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamEventsQuery('frc604').cache_key in cache_keys)
        self.assertTrue(
            TeamYearEventsQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(
            TeamYearEventsQuery('frc604', 2015).cache_key in cache_keys)

    def test_event_details_updated(self):
        affected_refs = {
            'key': {
                ndb.Key(EventDetails, '2015casj'),
                ndb.Key(EventDetails, '2015cama')
            },
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.event_details_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 2)
        self.assertTrue(EventDetailsQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventDetailsQuery('2015cama').cache_key in cache_keys)

    def test_match_updated(self):
        affected_refs = {
            'key':
            {ndb.Key(Match, '2015casj_qm1'),
             ndb.Key(Match, '2015casj_qm2')},
            'event': {ndb.Key(Event, '2015casj'),
                      ndb.Key(Event, '2015cama')},
            'team_keys': {ndb.Key(Team, 'frc254'),
                          ndb.Key(Team, 'frc604')},
            'year': {2014, 2015},
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.match_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 12)
        self.assertTrue(MatchQuery('2015casj_qm1').cache_key in cache_keys)
        self.assertTrue(MatchQuery('2015casj_qm2').cache_key in cache_keys)
        self.assertTrue(EventMatchesQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventMatchesQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(
            TeamEventMatchesQuery('frc254', '2015casj').cache_key in
            cache_keys)
        self.assertTrue(
            TeamEventMatchesQuery('frc254', '2015cama').cache_key in
            cache_keys)
        self.assertTrue(
            TeamEventMatchesQuery('frc604', '2015casj').cache_key in
            cache_keys)
        self.assertTrue(
            TeamEventMatchesQuery('frc604', '2015cama').cache_key in
            cache_keys)
        self.assertTrue(
            TeamYearMatchesQuery('frc254', 2014).cache_key in cache_keys)
        self.assertTrue(
            TeamYearMatchesQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(
            TeamYearMatchesQuery('frc604', 2014).cache_key in cache_keys)
        self.assertTrue(
            TeamYearMatchesQuery('frc604', 2015).cache_key in cache_keys)

    def test_media_updated_team(self):
        affected_refs = {
            'references': {ndb.Key(Team, 'frc254'),
                           ndb.Key(Team, 'frc604')},
            'year': {2014, 2015},
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.media_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 10)
        self.assertTrue(
            TeamYearMediaQuery('frc254', 2014).cache_key in cache_keys)
        self.assertTrue(
            TeamYearMediaQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(TeamSocialMediaQuery('frc254').cache_key in cache_keys)
        self.assertTrue(
            TeamYearMediaQuery('frc604', 2014).cache_key in cache_keys)
        self.assertTrue(
            TeamYearMediaQuery('frc604', 2015).cache_key in cache_keys)
        self.assertTrue(TeamSocialMediaQuery('frc604').cache_key in cache_keys)
        self.assertTrue(
            EventTeamsMediasQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(
            EventTeamsMediasQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(
            EventTeamsPreferredMediasQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(
            EventTeamsPreferredMediasQuery('2015casj').cache_key in cache_keys)

    def test_media_updated_event(self):
        affected_refs = {
            'references': {ndb.Key(Event, '2016necmp')},
            'year': {2016},
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.media_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 1)
        self.assertTrue(EventMediasQuery('2016necmp').cache_key in cache_keys)

    def test_robot_updated(self):
        affected_refs = {
            'team': {ndb.Key(Team, 'frc254'),
                     ndb.Key(Team, 'frc604')},
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.robot_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 2)
        self.assertTrue(TeamRobotsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamRobotsQuery('frc604').cache_key in cache_keys)

    def test_team_updated(self):
        affected_refs = {
            'key': {ndb.Key(Team, 'frc254'),
                    ndb.Key(Team, 'frc604')},
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.team_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 13)
        self.assertTrue(TeamQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamQuery('frc604').cache_key in cache_keys)
        self.assertTrue(TeamListQuery(0).cache_key in cache_keys)
        self.assertTrue(TeamListQuery(1).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2015, 0).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2015, 1).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2010, 1).cache_key in cache_keys)
        self.assertTrue(DistrictTeamsQuery('2015fim').cache_key in cache_keys)
        self.assertTrue(DistrictTeamsQuery('2015mar').cache_key in cache_keys)
        self.assertTrue(DistrictTeamsQuery('2016ne').cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2010cama').cache_key in cache_keys)

    def test_eventteam_updated(self):
        affected_refs = {
            'event': {ndb.Key(Event, '2015casj'),
                      ndb.Key(Event, '2015cama')},
            'team': {ndb.Key(Team, 'frc254'),
                     ndb.Key(Team, 'frc604')},
            'year': {2014, 2015}
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.eventteam_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 18)
        self.assertTrue(TeamEventsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamEventsQuery('frc604').cache_key in cache_keys)
        self.assertTrue(
            TeamParticipationQuery('frc254').cache_key in cache_keys)
        self.assertTrue(
            TeamParticipationQuery('frc604').cache_key in cache_keys)
        self.assertTrue(
            TeamYearEventsQuery('frc254', 2014).cache_key in cache_keys)
        self.assertTrue(
            TeamYearEventsQuery('frc254', 2015).cache_key in cache_keys)
        self.assertTrue(
            TeamYearEventsQuery('frc604', 2014).cache_key in cache_keys)
        self.assertTrue(
            TeamYearEventsQuery('frc604', 2015).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2014, 0).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2014, 1).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2015, 0).cache_key in cache_keys)
        self.assertTrue(TeamListYearQuery(2015, 1).cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(EventTeamsQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(
            EventTeamsMediasQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(
            EventTeamsMediasQuery('2015casj').cache_key in cache_keys)
        self.assertTrue(
            EventTeamsPreferredMediasQuery('2015cama').cache_key in cache_keys)
        self.assertTrue(
            EventTeamsPreferredMediasQuery('2015casj').cache_key in cache_keys)

    def test_districtteam_updated(self):
        affected_refs = {
            'district_key':
            {ndb.Key(District, '2015fim'),
             ndb.Key(District, '2015mar')},
            'team': {ndb.Key(Team, 'frc254'),
                     ndb.Key(Team, 'frc604')}
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.districtteam_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 4)
        self.assertTrue(DistrictTeamsQuery('2015fim').cache_key in cache_keys)
        self.assertTrue(DistrictTeamsQuery('2015mar').cache_key in cache_keys)
        self.assertTrue(TeamDistrictsQuery('frc254').cache_key in cache_keys)
        self.assertTrue(TeamDistrictsQuery('frc604').cache_key in cache_keys)

    def test_district_updated(self):
        affected_refs = {
            'key': {ndb.Key(District, '2016ne')},
            'year': {2015, 2016},
            'abbreviation': {'ne', 'chs'}
        }
        cache_keys = [
            q.cache_key
            for q in get_affected_queries.district_updated(affected_refs)
        ]

        self.assertEqual(len(cache_keys), 11)
        self.assertTrue(DistrictsInYearQuery(2015).cache_key in cache_keys)
        self.assertTrue(DistrictsInYearQuery(2016).cache_key in cache_keys)
        self.assertTrue(DistrictHistoryQuery('ne').cache_key in cache_keys)
        self.assertTrue(DistrictHistoryQuery('chs').cache_key in cache_keys)
        self.assertTrue(DistrictQuery('2016ne').cache_key in cache_keys)
        self.assertTrue(TeamDistrictsQuery('frc604').cache_key in cache_keys)

        # Necessary because APIv3 Event models include the District model
        self.assertTrue(EventQuery('2016necmp').cache_key in cache_keys)
        self.assertTrue(EventListQuery(2016).cache_key in cache_keys)
        self.assertTrue(DistrictEventsQuery('2016ne').cache_key in cache_keys)
        self.assertTrue(TeamEventsQuery('frc125').cache_key in cache_keys)
        self.assertTrue(
            TeamYearEventsQuery('frc125', 2016).cache_key in cache_keys)
class TestListDistrictEventsController(unittest2.TestCase):
    def setUp(self):
        app = webapp2.WSGIApplication([webapp2.Route(r'/<district_abbrev:>/<year:>', ApiDistrictEventsController, methods=['GET'])], debug=True)
        self.testapp = webtest.TestApp(app)

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.district = District(
            id='2010ne',
            year=2010,
            abbreviation='ne',
            display_name='New England',
        )
        self.district.put()

        self.event = Event(
                id="2010sc",
                name="Palmetto Regional",
                event_type_enum=EventType.DISTRICT_CMP,
                district_key=ndb.Key(District, '2010ne'),
                short_name="Palmetto",
                event_short="sc",
                year=2010,
                end_date=datetime(2010, 03, 27),
                official=True,
                city="Clemson",
                state_prov="SC",
                country="USA",
                venue="Long Beach Arena",
                venue_address="Long Beach Arena\r\n300 East Ocean Blvd\r\nLong Beach, CA 90802\r\nUSA",
                start_date=datetime(2010, 03, 24),
                webcast_json="[{\"type\": \"twitch\", \"channel\": \"frcgamesense\"}]",
                website="http://www.firstsv.org",
        )
        self.event.put()

        self.event_details = EventDetails(
            id=self.event.key.id(),
            alliance_selections=[
                {"declines": [], "picks": ["frc971", "frc254", "frc1662"]},
                {"declines": [], "picks": ["frc1678", "frc368", "frc4171"]},
                {"declines": [], "picks": ["frc2035", "frc192", "frc4990"]},
                {"declines": [], "picks": ["frc1323", "frc846", "frc2135"]},
                {"declines": [], "picks": ["frc2144", "frc1388", "frc668"]},
                {"declines": [], "picks": ["frc1280", "frc604", "frc100"]},
                {"declines": [], "picks": ["frc114", "frc852", "frc841"]},
                {"declines": [], "picks": ["frc2473", "frc3256", "frc1868"]}
            ]
        )
        self.event_details.put()

    def tearDown(self):
        self.testbed.deactivate()

    def assertDistrictEvent(self, event):
        self.assertEqual(event["key"], self.event.key_name)
        self.assertEqual(event["name"], self.event.name)
        self.assertEqual(event["short_name"], self.event.short_name)
        self.assertEqual(event["official"], self.event.official)
        self.assertEqual(event["event_type_string"], self.event.event_type_str)
        self.assertEqual(event["event_type"], self.event.event_type_enum)
        self.assertEqual(event["event_district_string"], self.event.event_district_str)
        self.assertEqual(event["event_district"], self.event.event_district_enum)
        self.assertEqual(event["start_date"], self.event.start_date.date().isoformat())
        self.assertEqual(event["end_date"], self.event.end_date.date().isoformat())
        self.assertEqual(event["location"], self.event.location)
        self.assertEqual(event["venue_address"], self.event.venue_address.replace('\r\n', '\n'))
        self.assertEqual(event["webcast"], json.loads(self.event.webcast_json))
        self.assertEqual(event["alliances"], self.event.alliance_selections)
        self.assertEqual(event["website"], self.event.website)

    def testEventApi(self):
        response = self.testapp.get("/{}/2010".format(self.district.abbreviation), headers={"X-TBA-App-Id": "tba-tests:disstrict-controller-test:v01"})

        events = json.loads(response.body)
        self.assertDistrictEvent(events[0])
class TestFIRSTElasticSearchEventListParser(unittest2.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache(
        )  # Prevent data from leaking between tests

        self.ne_district = District(id='2015ne',
                                    abbreviation='ne',
                                    year=2015,
                                    elasticsearch_name='NE FIRST')
        self.ne_district.put()

    def tearDown(self):
        self.testbed.deactivate()

    def test_parse_event_list(self):
        with open('test_data/first_elasticsearch/2015_event_list.json',
                  'r') as f:
            events = FIRSTElasticSearchEventListParser(2015).parse(
                json.loads(f.read()))

            self.assertTrue(isinstance(events, list))

            self.assertEquals(
                len(events), 56 + 48 +
                5)  # 56 regionals, 48 districts, 5 district championships

    def test_parse_regional_event(self):
        with open('test_data/first_elasticsearch/2015_event_list.json',
                  'r') as f:
            events = FIRSTElasticSearchEventListParser(2015).parse(
                json.loads(f.read()))

            for event in events:
                if event.key_name == '2015nyny':
                    self.assertEquals(event.key_name, "2015nyny")
                    self.assertEquals(event.name, "New York City Regional")
                    self.assertEquals(event.short_name, "New York City")
                    self.assertEquals(event.event_short, "nyny")
                    self.assertEquals(event.official, True)
                    self.assertEquals(
                        event.start_date,
                        datetime.datetime(year=2015,
                                          month=3,
                                          day=12,
                                          hour=0,
                                          minute=0,
                                          second=0))
                    self.assertEquals(
                        event.end_date,
                        datetime.datetime(year=2015,
                                          month=3,
                                          day=15,
                                          hour=23,
                                          minute=59,
                                          second=59))
                    self.assertEquals(event.venue,
                                      "Jacob K. Javits Convention Center")
                    self.assertEquals(event.city, "New York")
                    self.assertEquals(event.state_prov, "NY")
                    self.assertEquals(event.postalcode, "10001")
                    self.assertEquals(event.country, "USA")
                    self.assertEquals(
                        event.venue_address,
                        "Jacob K. Javits Convention Center\n655 West 34th Street\nNew York, NY 10001\nUSA"
                    )
                    self.assertEquals(event.year, 2015)
                    self.assertEquals(event.event_type_enum,
                                      EventType.REGIONAL)
                    self.assertEquals(event.district_key, None)
                    self.assertEquals(event.first_eid, '13339')
                    self.assertEquals(event.website, 'http://www.nycfirst.org')

    def test_parse_district_event(self):
        with open('test_data/first_elasticsearch/2015_event_list.json',
                  'r') as f:
            events = FIRSTElasticSearchEventListParser(2015).parse(
                json.loads(f.read()))
            for event in events:
                if event.key_name == '2015cthar':
                    self.assertEquals(event.key_name, "2015cthar")
                    self.assertEquals(event.name,
                                      "NE District - Hartford Event")
                    self.assertEquals(event.short_name, "Hartford")
                    self.assertEquals(event.event_short, "cthar")
                    self.assertEquals(event.official, True)
                    self.assertEquals(
                        event.start_date,
                        datetime.datetime(year=2015,
                                          month=3,
                                          day=27,
                                          hour=0,
                                          minute=0,
                                          second=0))
                    self.assertEquals(
                        event.end_date,
                        datetime.datetime(year=2015,
                                          month=3,
                                          day=29,
                                          hour=23,
                                          minute=59,
                                          second=59))
                    self.assertEquals(event.venue,
                                      "Hartford Public High School")
                    self.assertEquals(event.city, "Hartford")
                    self.assertEquals(event.state_prov, "CT")
                    self.assertEquals(event.postalcode, "06105")
                    self.assertEquals(event.country, "USA")
                    self.assertEquals(
                        event.venue_address,
                        "Hartford Public High School\n55 Forest Street\nHartford, CT 06105\nUSA"
                    )
                    self.assertEquals(event.year, 2015)
                    self.assertEquals(event.event_type_enum,
                                      EventType.DISTRICT)
                    self.assertEquals(event.district_key.id(), '2015ne')
                    self.assertEqual(event.district_key, self.ne_district.key)
                    self.assertEquals(event.first_eid, '13443')
                    self.assertEquals(event.website, 'http://www.nefirst.org/')

    def test_parse_district_cmp(self):
        with open('test_data/first_elasticsearch/2015_event_list.json',
                  'r') as f:
            events = FIRSTElasticSearchEventListParser(2015).parse(
                json.loads(f.read()))
            for event in events:
                if event.key_name == '2015necmp':
                    self.assertEquals(event.key_name, "2015necmp")
                    self.assertEquals(
                        event.name,
                        "NE FIRST District Championship presented by United Technologies"
                    )
                    self.assertEquals(event.short_name, "NE FIRST")
                    self.assertEquals(event.event_short, "necmp")
                    self.assertEquals(event.official, True)
                    self.assertEquals(
                        event.start_date,
                        datetime.datetime(year=2015,
                                          month=4,
                                          day=8,
                                          hour=0,
                                          minute=0,
                                          second=0))
                    self.assertEquals(
                        event.end_date,
                        datetime.datetime(year=2015,
                                          month=4,
                                          day=11,
                                          hour=23,
                                          minute=59,
                                          second=59))
                    self.assertEquals(event.venue,
                                      "Sports and Recreation Center, WPI")
                    self.assertEquals(event.city, "Worcester")
                    self.assertEquals(event.state_prov, "MA")
                    self.assertEquals(event.postalcode, "01609")
                    self.assertEquals(event.country, "USA")
                    self.assertEquals(
                        event.venue_address,
                        "Sports and Recreation Center, WPI\n100 Institute Road\nWorcester, MA 01609\nUSA"
                    )
                    self.assertEquals(event.year, 2015)
                    self.assertEquals(event.event_type_enum,
                                      EventType.DISTRICT_CMP)
                    self.assertEquals(event.district_key.id(), '2015ne')
                    self.assertEqual(event.district_key, self.ne_district.key)
                    self.assertEquals(event.first_eid, '13423')
                    self.assertEquals(event.website,
                                      'http:///www.nefirst.org/')
class TestEventController(unittest2.TestCase):

    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        app = webapp2.WSGIApplication([
            RedirectRoute(r'/event/<event_key>', EventDetail, 'event-detail'),
            RedirectRoute(r'/event/<event_key>/insights', EventInsights, 'event-insights'),
            RedirectRoute(r'/events/<year:[0-9]+>', EventList, 'event-list-year'),
            RedirectRoute(r'/events', EventList, 'event-list'),
        ])
        self.testapp = webtest.TestApp(app)

        self.district = District(
            id='2016ne',
            abbreviation='ne',
            year=2016,
            display_name='New England'
        )
        self.district.put()

        self.event1 = Event(
                id="2016necmp",
                name="New England District Championship",
                event_type_enum=EventType.DISTRICT_CMP,
                district_key=ndb.Key(District, '2016ne'),
                short_name="New England",
                event_short="necmp",
                year=2016,
                end_date=datetime(2016, 03, 27),
                official=True,
                city='Hartford',
                state_prov='CT',
                country='USA',
                venue="Some Venue",
                venue_address="Some Venue, Hartford, CT, USA",
                timezone_id="America/New_York",
                start_date=datetime(2016, 03, 24),
                webcast_json="[{\"type\": \"twitch\", \"channel\": \"frcgamesense\"}]",
                website="http://www.firstsv.org",
        )
        self.event1.put()

        # To test that /events defaults to current year
        this_year = datetime.now().year
        self.event2 = Event(
                id="{}necmp".format(this_year),
                name="New England District Championship",
                event_type_enum=EventType.DISTRICT_CMP,
                district_key=ndb.Key(District, '2016ne'),
                short_name="New England",
                event_short="necmp",
                year=this_year,
                end_date=datetime(this_year, 03, 27),
                official=True,
                city='Hartford',
                state_prov='CT',
                country='USA',
                venue="Some Venue",
                venue_address="Some Venue, Hartford, CT, USA",
                timezone_id="America/New_York",
                start_date=datetime(this_year, 03, 24),
                webcast_json="[{\"type\": \"twitch\", \"channel\": \"frcgamesense\"}]",
                website="http://www.firstsv.org",
        )
        self.event2.put()

        self.event1_details = EventDetails(
            id=self.event1.key.id(),
            predictions={"ranking_prediction_stats": {'qual': None, 'playoff': None}, "match_predictions": {'qual': None, 'playoff': None}, "ranking_predictions": None, "match_prediction_stats": {'qual': None, 'playoff': None}}
        )
        self.event1_details.put()

        self.event2_details = EventDetails(
            id=self.event2.key.id(),
            predictions={"ranking_prediction_stats": {'qual': None, 'playoff': None}, "match_predictions": {'qual': None, 'playoff': None}, "ranking_predictions": None, "match_prediction_stats": {'qual': None, 'playoff': None}}
        )
        self.event2_details.put()

    def tearDown(self):
        self.testbed.deactivate()

    def testEventListDefaultYear(self):
        response = self.testapp.get("/events")
        self.assertEqual(response.status_int, 200)

    def testEventListExplicitYear(self):
        response = self.testapp.get("/events/2015")
        self.assertEqual(response.status_int, 200)

    def testEventListNoEvents(self):
        response = self.testapp.get("/events/2014")
        self.assertEqual(response.status_int, 200)

    def testEventDetails(self):
        response = self.testapp.get("/event/2016necmp")
        self.assertEqual(response.status_int, 200)

    def testEventDetailsNotFound(self):
        response = self.testapp.get("/event/2016meow", status=404)
        self.assertEqual(response.status_int, 404)

    def testEventInsights(self):
        response = self.testapp.get("/event/2016necmp/insights")
        self.assertEqual(response.status_int, 200)

    def testEventInsightsNotFound(self):
        response = self.testapp.get("/event/2016meow/insights", status=404)
        self.assertEqual(response.status_int, 404)
Esempio n. 11
0
class TestListDistrictEventsController(unittest2.TestCase):
    def setUp(self):
        app = webapp2.WSGIApplication([webapp2.Route(r'/<district_abbrev:>/<year:>', ApiDistrictEventsController, methods=['GET'])], debug=True)
        self.testapp = webtest.TestApp(app)

        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_urlfetch_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.district = District(
            id='2010ne',
            year=2010,
            abbreviation='ne',
            display_name='New England',
        )
        self.district.put()

        self.event = Event(
            id="2010sc",
            name="Palmetto Regional",
            event_type_enum=EventType.DISTRICT_CMP,
            district_key=ndb.Key(District, '2010ne'),
            short_name="Palmetto",
            event_short="sc",
            year=2010,
            end_date=datetime(2010, 03, 27),
            official=True,
            city="Clemson",
            state_prov="SC",
            country="USA",
            venue="Long Beach Arena",
            venue_address="Long Beach Arena\r\n300 East Ocean Blvd\r\nLong Beach, CA 90802\r\nUSA",
            start_date=datetime(2010, 03, 24),
            webcast_json="[{\"type\": \"twitch\", \"channel\": \"frcgamesense\"}]",
            website="http://www.firstsv.org"
        )
        self.event.put()

        self.event_details = EventDetails(
            id=self.event.key.id(),
            alliance_selections=[
                {"declines": [], "picks": ["frc971", "frc254", "frc1662"]},
                {"declines": [], "picks": ["frc1678", "frc368", "frc4171"]},
                {"declines": [], "picks": ["frc2035", "frc192", "frc4990"]},
                {"declines": [], "picks": ["frc1323", "frc846", "frc2135"]},
                {"declines": [], "picks": ["frc2144", "frc1388", "frc668"]},
                {"declines": [], "picks": ["frc1280", "frc604", "frc100"]},
                {"declines": [], "picks": ["frc114", "frc852", "frc841"]},
                {"declines": [], "picks": ["frc2473", "frc3256", "frc1868"]}
            ]
        )
        self.event_details.put()

    def tearDown(self):
        self.testbed.deactivate()

    def assertDistrictEvent(self, event):
        self.assertEqual(event["key"], self.event.key_name)
        self.assertEqual(event["name"], self.event.name)
        self.assertEqual(event["short_name"], self.event.short_name)
        self.assertEqual(event["official"], self.event.official)
        self.assertEqual(event["event_type_string"], self.event.event_type_str)
        self.assertEqual(event["event_type"], self.event.event_type_enum)
        self.assertEqual(event["event_district_string"], self.event.event_district_str)
        self.assertEqual(event["event_district"], self.event.event_district_enum)
        self.assertEqual(event["start_date"], self.event.start_date.date().isoformat())
        self.assertEqual(event["end_date"], self.event.end_date.date().isoformat())
        self.assertEqual(event["location"], self.event.location)
        self.assertEqual(event["venue_address"], self.event.venue_address.replace('\r\n', '\n'))
        self.assertEqual(event["webcast"], json.loads(self.event.webcast_json))
        self.assertEqual(event["alliances"], self.event.alliance_selections)
        self.assertEqual(event["website"], self.event.website)

    def test_event_api(self):
        response = self.testapp.get("/{}/2010".format(self.district.abbreviation), headers={"X-TBA-App-Id": "tba-tests:disstrict-controller-test:v01"})

        events = json.loads(response.body)
        self.assertDistrictEvent(events[0])
class TestEventController(unittest2.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache(
        )  # Prevent data from leaking between tests

        app = webapp2.WSGIApplication([
            RedirectRoute(r'/event/<event_key>', EventDetail, 'event-detail'),
            RedirectRoute(r'/event/<event_key>/insights', EventInsights,
                          'event-insights'),
            RedirectRoute(r'/events/<year:[0-9]+>', EventList,
                          'event-list-year'),
            RedirectRoute(r'/events', EventList, 'event-list'),
        ])
        self.testapp = webtest.TestApp(app)

        self.district = District(id='2016ne',
                                 abbreviation='ne',
                                 year=2016,
                                 display_name='New England')
        self.district.put()

        self.event1 = Event(
            id="2016necmp",
            name="New England District Championship",
            event_type_enum=EventType.DISTRICT_CMP,
            district_key=ndb.Key(District, '2016ne'),
            short_name="New England",
            event_short="necmp",
            year=2016,
            end_date=datetime(2016, 03, 27),
            official=True,
            city='Hartford',
            state_prov='CT',
            country='USA',
            venue="Some Venue",
            venue_address="Some Venue, Hartford, CT, USA",
            timezone_id="America/New_York",
            start_date=datetime(2016, 03, 24),
            webcast_json=
            "[{\"type\": \"twitch\", \"channel\": \"frcgamesense\"}]",
            website="http://www.firstsv.org",
        )
        self.event1.put()

        # To test that /events defaults to current year
        this_year = datetime.now().year
        self.event2 = Event(
            id="{}necmp".format(this_year),
            name="New England District Championship",
            event_type_enum=EventType.DISTRICT_CMP,
            district_key=ndb.Key(District, '2016ne'),
            short_name="New England",
            event_short="necmp",
            year=this_year,
            end_date=datetime(this_year, 03, 27),
            official=True,
            city='Hartford',
            state_prov='CT',
            country='USA',
            venue="Some Venue",
            venue_address="Some Venue, Hartford, CT, USA",
            timezone_id="America/New_York",
            start_date=datetime(this_year, 03, 24),
            webcast_json=
            "[{\"type\": \"twitch\", \"channel\": \"frcgamesense\"}]",
            website="http://www.firstsv.org",
        )
        self.event2.put()

        self.event1_details = EventDetails(id=self.event1.key.id(),
                                           predictions={
                                               "ranking_prediction_stats": {
                                                   'qual': None,
                                                   'playoff': None
                                               },
                                               "match_predictions": {
                                                   'qual': None,
                                                   'playoff': None
                                               },
                                               "ranking_predictions": None,
                                               "match_prediction_stats": {
                                                   'qual': None,
                                                   'playoff': None
                                               }
                                           })
        self.event1_details.put()

        self.event2_details = EventDetails(id=self.event2.key.id(),
                                           predictions={
                                               "ranking_prediction_stats": {
                                                   'qual': None,
                                                   'playoff': None
                                               },
                                               "match_predictions": {
                                                   'qual': None,
                                                   'playoff': None
                                               },
                                               "ranking_predictions": None,
                                               "match_prediction_stats": {
                                                   'qual': None,
                                                   'playoff': None
                                               }
                                           })
        self.event2_details.put()

    def tearDown(self):
        self.testbed.deactivate()

    def testEventListDefaultYear(self):
        response = self.testapp.get("/events")
        self.assertEqual(response.status_int, 200)

    def testEventListExplicitYear(self):
        response = self.testapp.get("/events/2015")
        self.assertEqual(response.status_int, 200)

    def testEventListNoEvents(self):
        response = self.testapp.get("/events/2014")
        self.assertEqual(response.status_int, 200)

    def testEventDetails(self):
        response = self.testapp.get("/event/2016necmp")
        self.assertEqual(response.status_int, 200)

    def testEventDetailsNotFound(self):
        response = self.testapp.get("/event/2016meow", status=404)
        self.assertEqual(response.status_int, 404)

    def testEventInsights(self):
        response = self.testapp.get("/event/2016necmp/insights")
        self.assertEqual(response.status_int, 200)

    def testEventInsightsNotFound(self):
        response = self.testapp.get("/event/2016meow/insights", status=404)
        self.assertEqual(response.status_int, 404)