Example #1
0
 def __init__(self,
              dbHost=os.environ["DB_HOST"],
              dbPort=int(os.environ["DB_PORT"]),
              dbAuthName=(os.environ["DB_AUTH_NAME"]
                          if "DB_AUTH_NAME" in os.environ else ""),
              dbName=os.environ["DB_NAME"],
              dbUser=os.environ["DB_USER"],
              dbUserPwd=os.environ["DB_USER_PWD"],
              dbSSL=("DB_USE_SSL" in os.environ
                     and util.str2bool(os.environ["DB_USE_SSL"])),
              dbReplicaSet=(os.environ["DB_REPL_SET"]
                            if "DB_REPL_SET" in os.environ else ""),
              dbAppName=(os.environ["DB_APP_NAME"]
                         if "DB_APP_NAME" in os.environ else "")):
     self._entity_manager = EntityManager(dbHost, dbPort, dbAuthName,
                                          dbName, dbUser, dbUserPwd, dbSSL,
                                          dbReplicaSet, dbAuthName)
     self._nflapi = nflapi.Client.Client()
     self._team_mgr = None
     self._roster_mgr = None
     self._sched_mgr = None
     self._plprof_mgr = None
     self._plgmlg_mgr = None
     self._gmsum_mgr = None
     self._gmscr_mgr = None
     self._gmdrv_mgr = None
     self._gmplay_mgr = None
class TestTeamManagerFacade(unittest.TestCase):
    def setUp(self):
        self.entityName = "team"
        self.entmgr = EntityManager()
        self.datamgr = TeamManagerFacade(self.entmgr)

    def tearDown(self):
        util.runCoroutine(self.datamgr.drop())
        self.entmgr.dispose()

    def test_sync_initializes_collection(self):
        recs = util.runCoroutine(self.datamgr.sync())
        self.assertGreater(len(recs), 0, "sync returned 0 records")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs, "db records differ")

    def test_sync_only_inserts_new(self):
        recs = util.runCoroutine(self.datamgr.sync())
        self.assertGreater(len(recs), 0, "sync returned 0 records")
        recs2 = util.runCoroutine(self.datamgr.sync())
        self.assertEqual(len(recs2), 0, "sync returned 0 records")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs, "db records differ")

    def test_save_appends(self):
        recs = util.runCoroutine(self.datamgr.sync())
        arec = util.runCoroutine(self.datamgr.save([{"team": "NX"}]))
        recs.extend(arec)
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs), len(recs), "record count differs")
        self.assertEqual(dbrecs, recs, "db records differ")

    def test_find_no_constraints(self):
        recs = util.runCoroutine(
            self.entmgr.save(self.entityName, [{
                "team": "KC"
            }, {
                "team": "PIT"
            }]))
        for rec in recs:
            del rec["_id"]
        dbrecs = util.runCoroutine(self.datamgr.find())
        self.assertEqual(dbrecs, recs, "db records differ")

    def test_find_constraint(self):
        recs = util.runCoroutine(
            self.entmgr.save(self.entityName, [{
                "team": "KC"
            }, {
                "team": "PIT"
            }]))
        for rec in recs:
            del rec["_id"]
        dbrecs = util.runCoroutine(self.datamgr.find(teams=["KC"]))
        self.assertEqual(dbrecs, [recs[0]], "db records differ")
Example #3
0
 def setUp(self):
     logging.basicConfig(level=logging.INFO)
     self.entmgr = EntityManager(dbName="nflapidb_ut")
 def setUp(self):
     self.entityName = "game_drive"
     self.entmgr = EntityManager()
     self.rostmgr = None
class TestGameDriveManagerFacade(unittest.TestCase):
    def setUp(self):
        self.entityName = "game_drive"
        self.entmgr = EntityManager()
        self.rostmgr = None

    def tearDown(self):
        util.runCoroutine(self.entmgr.drop(self.entityName))
        if self.rostmgr is not None:
            util.runCoroutine(self.entmgr.drop(self.rostmgr.entityName))
        self.entmgr.dispose()

    def _getMockGameDriveManager(self, scheduleData: List[dict],
                                 gmdrvData: List[dict]):
        apiClient = MockApiClient(gmdrvData)
        schmgr = MockScheduleManagerFacade(self.entmgr, scheduleData)
        self.datamgr = GameDriveManagerFacade(self.entmgr, apiClient, schmgr)
        return self.datamgr

    def _getTestDataPath(self, fname: str = None) -> str:
        path = os.path.join(os.path.dirname(__file__), "data")
        if fname is not None:
            path = os.path.join(path, fname)
        return path

    def _getScheduleData(self, weeks: List[int] = None) -> List[dict]:
        if weeks is None:
            weeks = [13, 14]
        with open(self._getTestDataPath("schedule_2019.json"), "rt") as fp:
            return [r for r in json.load(fp) if r["week"] in weeks]

    def _getGameDriveData(self, weeks: List[int] = None) -> List[dict]:
        if weeks is None:
            weeks = [13, 14]
        data = []
        for week in weeks:
            with open(
                    self._getTestDataPath(f"game_drive_2019_reg_{week}.json"),
                    "rt") as fp:
                data.extend(json.load(fp))
        return data

    def test_sync_initializes_collection(self):
        schdata = self._getScheduleData()
        gsdata = self._getGameDriveData()
        gsmgr = self._getMockGameDriveManager(schdata, gsdata)
        recs = util.runCoroutine(gsmgr.sync())
        self.assertEqual(len(recs), len(gsdata),
                         "returned record counts differ")
        dbrecs = util.runCoroutine(gsmgr.find())
        for r in recs:
            del r["_id"]
        self.assertEqual(len(dbrecs), len(recs), "db record counts differ")
        self.assertEqual(dbrecs, recs, "db records differ")
        apireqs = gsmgr._apiClient.getRequestedSchedules()
        self.assertEqual(len(apireqs), len(schdata),
                         "api request record counts differ")
        self.assertEqual(apireqs, schdata, "api request records differ")

    def test_sync_no_new_finished_noop(self):
        schdata = self._getScheduleData()
        gsdata = self._getGameDriveData([13])
        gsmgr = self._getMockGameDriveManager(schdata, gsdata)
        recs1 = util.runCoroutine(gsmgr.sync())
        self.assertEqual(len(recs1), len(gsdata),
                         "first returned record counts differ")
        recs2 = util.runCoroutine(gsmgr.sync())
        self.assertEqual(len(recs2), 0, "second returned record counts differ")
        dbrecs = util.runCoroutine(gsmgr.find())
        self.assertEqual(len(dbrecs), len(recs1), "db record counts differ")

    def test_sync_new_finished_adds(self):
        schdata1 = self._getScheduleData()
        schdata2 = schdata1.copy()
        reqsch2 = []
        for r in schdata2:
            if not r["finished"]:
                r["finished"] = True
                reqsch2.append(r)
        gsdata1 = self._getGameDriveData([13])
        gsdata2 = self._getGameDriveData([14])
        gsmgr = self._getMockGameDriveManager(schdata1, gsdata1)
        recs1 = util.runCoroutine(gsmgr.sync())
        self.assertEqual(len(recs1), len(gsdata1),
                         "first returned record counts differ")
        gsmgr = self._getMockGameDriveManager(schdata2, gsdata2)
        recs2 = util.runCoroutine(gsmgr.sync())
        self.assertEqual(len(recs2), len(gsdata2),
                         "second returned record counts differ")
        dbrecs = util.runCoroutine(gsmgr.find())
        recs = recs1 + recs2
        for r in recs:
            del r["_id"]
        self.assertEqual(len(dbrecs), len(recs), "db record counts differ")
        self.assertEqual(dbrecs, recs, "db records differ")
        apireqs = gsmgr._apiClient.getRequestedSchedules()
        self.assertEqual(len(apireqs), len(reqsch2),
                         "api request record counts differ")
        self.assertEqual(apireqs, reqsch2, "api request records differ")
Example #6
0
 def setUp(self):
     self.entityName = "player_gamelog"
     self.entmgr = EntityManager()
Example #7
0
class TestPlayerGamelogManagerFacade(unittest.TestCase):
    def setUp(self):
        self.entityName = "player_gamelog"
        self.entmgr = EntityManager()

    def tearDown(self):
        util.runCoroutine(self.entmgr.drop(self.entityName))
        util.runCoroutine(self.entmgr.drop(f"{self.entityName}_process"))
        self.entmgr.dispose()

    def _getMockPlayerGamelogManager(self,
                                     rosterData: List[dict],
                                     gamelogData: List[dict],
                                     dataExpired: bool = None):
        apiClient = MockApiClient(gamelogData)
        rmgr = MockRosterManagerFacade(self.entmgr, apiClient, rosterData)
        self.datamgr = MockPlayerGamelogManagerFacade(self.entmgr, apiClient,
                                                      rmgr, dataExpired)
        return self.datamgr

    def _getPlayerGamelogManager(self):
        self.datamgr = PlayerGamelogManagerFacade(self.entmgr)
        return self.datamgr

    def _compareGL(self, testrecs: List[dict], exprecs: List[dict]):
        testrecs = __sortgl__(testrecs)
        exprecs = __sortgl__(__getUniqueGL__(exprecs))
        self.assertEqual(len(testrecs), len(exprecs), "record counts differs")
        for i in range(0, len(testrecs)):
            try:
                self.assertEqual(testrecs[i], exprecs[i],
                                 f"record {i} differs")
            except AssertionError as e:
                raise e

    def test_sync_initializes_collection_one_team(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        rmgr = self._getMockPlayerGamelogManager(rosterData=rstdata,
                                                 gamelogData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata),
                         "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self._compareGL(dbrecs, recs)
        self.assertEqual(rmgr._apiClient.getRequestedRosters(), rstdata,
                         "requested rosters differs")

    def test_sync_initializes_collection_two_teams(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            rstdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockPlayerGamelogManager(rosterData=rstdata,
                                                 gamelogData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata),
                         "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self._compareGL(dbrecs, recs)
        self.assertEqual(rmgr._apiClient.getRequestedRosters(), rstdata,
                         "requested rosters differs")

    def test_sync_only_updates_records_with_team_change(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            rstdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockPlayerGamelogManager(rosterData=rstdata,
                                                 gamelogData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        xreqrec = []
        for rec in rstdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                xreqrec.append(rec)
        xrec = []
        for rec in srcdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                crec = rec.copy()
                # Since the team is changing the previous_teams attribute should be set
                crec["previous_teams"] = ["PIT"]
                xrec.append(crec)
        rmgr = self._getMockPlayerGamelogManager(rosterData=rstdata,
                                                 gamelogData=srcdata,
                                                 dataExpired=False)
        recs = util.runCoroutine(rmgr.sync())
        reqrec = rmgr._apiClient.getRequestedRosters()
        self.assertEqual(len(reqrec), len(xreqrec),
                         "requested roster lengths differs")
        self.assertEqual(reqrec, xreqrec, "requested rosters differs")
        self.assertEqual(len(recs), 24, "sync returned record count differs")
        dbrecs = util.runCoroutine(
            self.entmgr.find(self.entityName,
                             query={"profile_id": 2560950},
                             projection={"_id": False}))
        self.assertEqual(len(dbrecs), 24, "db record counts differ")
        self._compareGL(dbrecs, xrec)

    def test_sync_updates_nothing_with_no_team_change(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            rstdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockPlayerGamelogManager(rosterData=rstdata,
                                                 gamelogData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        rmgr = self._getMockPlayerGamelogManager(rosterData=rstdata,
                                                 gamelogData=srcdata,
                                                 dataExpired=False)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), 0, "sync returned record count differs")
        self.assertEqual(rmgr._apiClient.getRequestedRosters(), [],
                         "requested rosters differs")

    def test_sync_updates_all_with_all(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            rstdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockPlayerGamelogManager(rosterData=rstdata,
                                                 gamelogData=srcdata)
        util.runCoroutine(rmgr.sync())

        def pidmap(recs: List[dict]) -> dict:
            return dict(zip([_["profile_id"] for _ in recs], recs))

        rmap = pidmap(rstdata.copy())
        usrcdata = []
        for rec in srcdata:
            pid = rec["profile_id"]
            t = random.choice(["KC", "PIT"])
            rmap[pid]["team"] = t
            rec["team"] = t
            usrcdata.append(rec)
        rmgr = self._getMockPlayerGamelogManager(rosterData=rmap.values(),
                                                 gamelogData=usrcdata)
        util.runCoroutine(rmgr.sync(all=True))
        dbrecs = util.runCoroutine(
            self.entmgr.find(self.entityName, projection={"_id": False}))
        self._compareGL(dbrecs, usrcdata)

    def test_sync_updates_current_season_only_with_week_diff(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            rstdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            alldata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_pit.json"), "rt") as fp:
            alldata.extend(json.load(fp))

        def insmaxgame(d: dict,
                       rec: dict,
                       path: List[str] = ["season", "season_type", "wk"]):
            for k in path:
                if len(d) > 0:
                    dv = list(d.keys())[0]
                    del d[dv]
                v = rec[k]
                d[v] = {}
                d = d[v]

        def maxgame(recs: dict) -> dict:
            st = ["preseason", "regular_season", "postseason"]
            md = {}
            for rec in recs:
                d = md
                if len(d) == 0:
                    insmaxgame(d, rec)
                else:
                    v = rec["season"]
                    cv = list(d.keys())[0]
                    if v > cv:
                        insmaxgame(d, rec)
                    elif v == cv:
                        d = d[cv]
                        v = rec["season_type"]
                        cv = list(d.keys())[0]
                        if st.index(v) > st.index(cv):
                            insmaxgame(d, rec, ["season_type", "wk"])
                        elif st.index(v) == st.index(cv):
                            d = d[cv]
                            v = rec["wk"]
                            cv = list(d.keys())[0]
                            if v > cv:
                                insmaxgame(d, rec, ["wk"])
            return md

        def ismaxgame(rec: dict, mgd: dict) -> bool:
            b = False
            d = mgd
            for k in ["season", "season_type", "wk"]:
                v = rec[k]
                if v in d:
                    d = d[v]
                    if len(d) == 0:
                        b = True
                else:
                    break
            return b

        mg = maxgame(alldata)
        srcdata1 = []
        srcdata2 = []
        for rec in alldata:
            if not ismaxgame(rec, mg):
                srcdata1.append(rec)
            srcdata2.append(rec)
        rmgr = self._getMockPlayerGamelogManager(rosterData=rstdata,
                                                 gamelogData=srcdata1)
        util.runCoroutine(rmgr.sync())
        rmgr = self._getMockPlayerGamelogManager(rosterData=rstdata,
                                                 gamelogData=srcdata2)
        util.runCoroutine(
            rmgr._updateDataExpired(datetime.datetime.today() -
                                    datetime.timedelta(weeks=1)))
        util.runCoroutine(rmgr.sync())
        dbrecs = util.runCoroutine(
            self.entmgr.find(self.entityName, projection={"_id": False}))
        self._compareGL(dbrecs, srcdata2)
        self.assertEqual(rmgr._apiClient.getRequestedSeasons(),
                         set([rmgr._currentSeason]),
                         "requested seasons differs")

    def test_save_appends(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            kcrdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            kcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_pit.json"), "rt") as fp:
            pitdata = json.load(fp)
        rmgr = self._getMockPlayerGamelogManager(rosterData=kcrdata,
                                                 gamelogData=kcdata.copy())
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(kcdata), "sync record count differs")
        recs.extend(util.runCoroutine(rmgr.save(pitdata.copy())))
        self.assertEqual(len(recs),
                         len(kcdata) + len(pitdata),
                         "save record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self._compareGL(dbrecs, recs)

    def test_save_updates_previous_team(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            srcrdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            srcrdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            kcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_pit.json"), "rt") as fp:
            pitdata = json.load(fp)
        srcdata = kcdata.copy()
        srcdata.extend(pitdata.copy())
        rmgr = self._getMockPlayerGamelogManager(rosterData=srcrdata,
                                                 gamelogData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata), "sync record count differs")
        for rec in pitdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                kcdata.append(rec)
        recs2 = util.runCoroutine(rmgr.save(kcdata.copy()))
        self.assertEqual(len(recs2), len(kcdata), "save record count differs")
        dbrecs = util.runCoroutine(
            self.entmgr.find(self.entityName, projection={"_id": False}))
        for rec in srcdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                rec["previous_teams"] = ["PIT"]
        self._compareGL(dbrecs, srcdata)

    def test_delete_team(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            kcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_pit.json"), "rt") as fp:
            pitdata = json.load(fp)
        srcdata = kcdata.copy()
        srcdata.extend(pitdata.copy())
        rmgr = self._getPlayerGamelogManager()
        recs = util.runCoroutine(rmgr.save(srcdata))
        self.assertEqual(len(recs), len(srcdata),
                         "save returned record count differs")
        dcount = util.runCoroutine(rmgr.delete(teams=["PIT"]))
        self.assertEqual(dcount, len(pitdata),
                         "delete returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        for rec in dbrecs:
            del rec["_id"]
        self._compareGL(dbrecs, kcdata)

    def test_delete_profile_id(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_gamelog_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        xdelrecs = [_ for _ in srcdata if _["profile_id"] == 2562399]
        xdata = [_ for _ in srcdata if _["profile_id"] != 2562399]
        rmgr = self._getPlayerGamelogManager()
        recs = util.runCoroutine(rmgr.save(srcdata))
        self.assertEqual(len(recs), len(srcdata),
                         "save returned record count differs")
        dcount = util.runCoroutine(rmgr.delete(profile_ids=[2562399]))
        self.assertEqual(dcount, len(xdelrecs),
                         "delete returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        for rec in dbrecs:
            del rec["_id"]
        self._compareGL(dbrecs, xdata)
Example #8
0
 def setUp(self):
     self.entityName = "game_summary"
     self.entmgr = EntityManager()
     self.rostmgr = None
 def setUp(self):
     self.entityName = "player_profile"
     self.entmgr = EntityManager()
class TestPlayerProfileManagerFacade(unittest.TestCase):
    def setUp(self):
        self.entityName = "player_profile"
        self.entmgr = EntityManager()

    def tearDown(self):
        util.runCoroutine(self.entmgr.drop(self.entityName))
        self.entmgr.dispose()

    def _getMockPlayerProfileManager(self, rosterData: List[dict],
                                     profileData: List[dict]):
        apiClient = MockApiClient(profileData)
        rmgr = MockRosterManagerFacade(self.entmgr, apiClient, rosterData)
        self.datamgr = PlayerProfileManagerFacade(self.entmgr, apiClient, rmgr)
        return self.datamgr

    def _getPlayerProfileManager(self):
        self.datamgr = PlayerProfileManagerFacade(self.entmgr)
        return self.datamgr

    def test_sync_initializes_collection_one_team(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        rmgr = self._getMockPlayerProfileManager(rosterData=rstdata,
                                                 profileData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata),
                         "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs, "db records differ")
        self.assertEqual(rmgr._apiClient.getRequestedRosters(), rstdata,
                         "requested rosters differs")

    def test_sync_initializes_collection_two_teams(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            rstdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockPlayerProfileManager(rosterData=rstdata,
                                                 profileData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata),
                         "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs, "db records differ")
        self.assertEqual(rmgr._apiClient.getRequestedRosters(), rstdata,
                         "requested rosters differs")

    def test_sync_only_updates_records_with_team_change(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            rstdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockPlayerProfileManager(rosterData=rstdata,
                                                 profileData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        xreqrec = []
        for rec in rstdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                xreqrec.append(rec)
        xrec = []
        for rec in srcdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                crec = rec.copy()
                # Since the team is changing the previous_teams attribute should be set
                crec["previous_teams"] = ["PIT"]
                xrec.append(crec)
        rmgr = self._getMockPlayerProfileManager(rosterData=rstdata,
                                                 profileData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(rmgr._apiClient.getRequestedRosters(), xreqrec,
                         "requested rosters differs")
        self.assertEqual(len(recs), 1, "sync returned record count differs")
        dbrecs = util.runCoroutine(
            self.entmgr.find(self.entityName,
                             query={"profile_id": 2560950},
                             projection={"_id": False}))
        self.assertEqual(len(dbrecs), 1, "db record counts differ")
        self.assertEqual(dbrecs, xrec, "db records differ")

    def test_sync_updates_nothing_with_no_team_change(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            rstdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockPlayerProfileManager(rosterData=rstdata,
                                                 profileData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        rmgr = self._getMockPlayerProfileManager(rosterData=rstdata,
                                                 profileData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), 0, "sync returned record count differs")
        self.assertEqual(rmgr._apiClient.getRequestedRosters(), [],
                         "requested rosters differs")

    def test_sync_updates_all_with_all(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            rstdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            rstdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockPlayerProfileManager(rosterData=rstdata,
                                                 profileData=srcdata)
        recs = util.runCoroutine(rmgr.sync())

        def pidmap(recs: List[dict]) -> dict:
            return dict(zip([_["profile_id"] for _ in recs], recs))

        rmap = pidmap(rstdata.copy())
        pmap = pidmap(srcdata.copy())
        usrcdata = []
        for pid in rmap:
            t = random.choice(["KC", "PIT"])
            rmap[pid]["team"] = t
            pmap[pid]["team"] = t
            usrcdata.append(pmap[pid])
        rmgr = self._getMockPlayerProfileManager(rosterData=list(
            rmap.values()),
                                                 profileData=usrcdata)
        recs = util.runCoroutine(rmgr.sync(all=True))
        self.assertEqual(len(recs), len(usrcdata),
                         "sync returned record count differs")
        dbrecs = util.runCoroutine(
            self.entmgr.find(self.entityName, projection={"_id": False}))
        self.assertEqual(dbrecs, usrcdata, "db records differ")

    def test_save_appends(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            kcrdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_kc.json"), "rt") as fp:
            kcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_pit.json"), "rt") as fp:
            pitdata = json.load(fp)
        rmgr = self._getMockPlayerProfileManager(rosterData=kcrdata,
                                                 profileData=kcdata.copy())
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(kcdata), "sync record count differs")
        recs.extend(util.runCoroutine(rmgr.save(pitdata.copy())))
        self.assertEqual(len(recs),
                         len(kcdata) + len(pitdata),
                         "save record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs), len(recs), "db record count differs")
        self.assertEqual(dbrecs, recs, "db records differ")

    def test_save_updates_previous_team(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_kc.json"), "rt") as fp:
            srcrdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "roster_pit.json"), "rt") as fp:
            srcrdata.extend(json.load(fp))
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_kc.json"), "rt") as fp:
            kcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_pit.json"), "rt") as fp:
            pitdata = json.load(fp)
        srcdata = kcdata.copy()
        srcdata.extend(pitdata.copy())
        rmgr = self._getMockPlayerProfileManager(rosterData=srcrdata,
                                                 profileData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata), "sync record count differs")
        for rec in pitdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                kcdata.append(rec)
        recs2 = util.runCoroutine(rmgr.save(kcdata.copy()))
        self.assertEqual(len(recs2), len(kcdata), "save record count differs")
        dbrecs = util.runCoroutine(
            self.entmgr.find(self.entityName, projection={"_id": False}))
        self.assertEqual(len(dbrecs), len(srcdata), "db record count differs")
        for rec in srcdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                rec["previous_teams"] = ["PIT"]
        self.assertEqual(dbrecs, srcdata, "db records differ")

    def test_delete_team(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_kc.json"), "rt") as fp:
            kcdata = json.load(fp)
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_pit.json"), "rt") as fp:
            pitdata = json.load(fp)
        srcdata = kcdata.copy()
        srcdata.extend(pitdata.copy())
        rmgr = self._getPlayerProfileManager()
        recs = util.runCoroutine(rmgr.save(srcdata))
        self.assertEqual(len(recs), len(srcdata),
                         "save returned record count differs")
        dcount = util.runCoroutine(rmgr.delete(teams=["PIT"]))
        self.assertEqual(dcount, len(pitdata),
                         "delete returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs), len(kcdata), "db record count differs")
        for rec in dbrecs:
            del rec["_id"]
        self.assertEqual(dbrecs, kcdata, "db records differ")

    def test_delete_profile_id(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "player_profile_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        rmgr = self._getPlayerProfileManager()
        recs = util.runCoroutine(rmgr.save(srcdata))
        self.assertEqual(len(recs), len(srcdata),
                         "save returned record count differs")
        dcount = util.runCoroutine(rmgr.delete(profile_ids=[2562399]))
        self.assertEqual(dcount, 1, "delete returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs),
                         len(srcdata) - 1, "db record count differs")
        xdata = [_ for _ in srcdata if _["profile_id"] != 2562399]
        self.assertEqual(dbrecs, xdata, "db records differ")
 def setUp(self):
     self.entityName = "roster"
     self.entmgr = EntityManager()
class TestRosterManagerFacade(unittest.TestCase):

    def setUp(self):
        self.entityName = "roster"
        self.entmgr = EntityManager()

    def tearDown(self):
        util.runCoroutine(self.entmgr.drop(self.entityName))
        self.entmgr.dispose()

    def _getMockRosterManager(self, teamData : List[dict], rosterData : List[dict], historicData : List[dict] = None):
        apiClient = MockApiClient(rosterData)
        tmmgr = MockTeamManagerFacade(self.entmgr, apiClient, teamData)
        self.datamgr = MockRosterManagerFacade(self.entmgr, apiClient, tmmgr, historicData)
        return self.datamgr

    def _getRosterManager(self):
        self.datamgr = RosterManagerFacade(self.entmgr)
        return self.datamgr

    def test_sync_initializes_collection_one_team(self):
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        rmgr = self._getMockRosterManager(teamData=[{"team": "KC"}], rosterData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata), "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs, "db records differ")
        self.assertEqual(rmgr._apiClient.getRequestedTeams(), set(["KC"]), "requested teams differs")

    def test_sync_initializes_collection_two_teams(self):
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockRosterManager(teamData=[{"team": "KC"}, {"team": "PIT"}], rosterData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata), "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs, "db records differ")
        self.assertEqual(rmgr._apiClient.getRequestedTeams(), set(["KC", "PIT"]), "requested teams differs")

    def test_sync_initializes_collection_with_historic_data(self):
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_pit.json"), "rt") as fp:
            histdata = json.load(fp)
        rmgr = self._getMockRosterManager(teamData=[{"team": "KC"}], rosterData=srcdata, historicData=histdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata) + len(histdata), "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs), len(srcdata) + len(histdata), "db record count differs")
        self.assertEqual(dbrecs, recs, "db records differ")
        self.assertEqual(rmgr._apiClient.getRequestedTeams(), set(["KC"]), "requested teams differs")

    def test_sync_initializes_collection_with_historic_data_with_previous_team(self):
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            histdata = json.load(fp)
            for rec in histdata:
                rec["team"] = "PIT"
        rmgr = self._getMockRosterManager(teamData=[{"team": "KC"}], rosterData=srcdata, historicData=histdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata) + len(histdata), "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs), len(srcdata), "db record count differs")
        for rec in dbrecs:
            self.assertTrue("previous_teams" in rec, "previous_teams not added to {}".format(rec["profile_id"]))
            self.assertEqual(rec["previous_teams"], ["PIT"], "previous_teams value not equal for {}".format(rec["profile_id"]))
        self.assertEqual(rmgr._apiClient.getRequestedTeams(), set(["KC"]), "requested teams differs")

    def test__getHistoricData(self):
        with open("data/historic_roster.json", "rt") as fp:
            hrdata = json.load(fp)
        rmgr = self._getRosterManager()
        self.assertEqual(rmgr._getHistoricData(), hrdata)

    def test_sync_stores_previous_team(self):
        teamData = [{"team": "KC"}, {"team": "PIT"}]
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_pit.json"), "rt") as fp:
            srcdata.extend(json.load(fp))
        rmgr = self._getMockRosterManager(teamData=teamData, rosterData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        for rec in srcdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
        rmgr = self._getMockRosterManager(teamData=teamData, rosterData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata), "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs, "db records differ")
        self.assertEqual(rmgr._apiClient.getRequestedTeams(), set(["KC", "PIT"]), "requested teams differs")
        xurecs = [_ for _ in dbrecs if _["profile_id"] == 2560950]
        self.assertEqual(len(xurecs), 1, "updated record count differs")
        self.assertTrue("previous_teams" in xurecs[0], "previous_teams attribute missing")
        self.assertEqual(xurecs[0]["previous_teams"], ["PIT"], "previous_teams value differs")

    def test_save_appends(self):
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            kcdata = json.load(fp)
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_pit.json"), "rt") as fp:
            pitdata = json.load(fp)
        rmgr = self._getMockRosterManager(teamData=[{"team": "KC"}], rosterData=kcdata.copy())
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(kcdata), "sync record count differs")
        recs.extend(util.runCoroutine(rmgr.save(pitdata.copy())))
        self.assertEqual(len(recs), len(kcdata) + len(pitdata), "save record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs), len(recs), "db record count differs")
        self.assertEqual(dbrecs, recs, "db records differ")

    def test_save_updates_previous_team(self):
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            kcdata = json.load(fp)
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_pit.json"), "rt") as fp:
            pitdata = json.load(fp)
        srcdata = kcdata.copy()
        srcdata.extend(pitdata.copy())
        rmgr = self._getMockRosterManager(teamData=[{"team": "KC"}, {"team": "PIT"}], rosterData=srcdata)
        recs = util.runCoroutine(rmgr.sync())
        self.assertEqual(len(recs), len(srcdata), "sync record count differs")
        for rec in pitdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                kcdata.append(rec)
        recs2 = util.runCoroutine(rmgr.save(kcdata.copy()))
        self.assertEqual(len(recs2), len(kcdata), "save record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs), len(srcdata), "db record count differs")
        for rec in srcdata:
            if rec["profile_id"] == 2560950:
                rec["team"] = "KC"
                rec["previous_teams"] = ["PIT"]
        self.assertEqual(dbrecs, srcdata, "db records differ")

    def test_delete_team(self):
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            kcdata = json.load(fp)
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_pit.json"), "rt") as fp:
            pitdata = json.load(fp)
        srcdata = kcdata.copy()
        srcdata.extend(pitdata.copy())
        rmgr = self._getRosterManager()
        recs = util.runCoroutine(rmgr.save(srcdata))
        self.assertEqual(len(recs), len(srcdata), "save returned record count differs")
        dcount = util.runCoroutine(rmgr.delete(teams=["PIT"]))
        self.assertEqual(dcount, len(pitdata), "delete returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs), len(kcdata), "db record count differs")
        for rec in dbrecs:
            del rec["_id"]
        self.assertEqual(dbrecs, kcdata, "db records differ")

    def test_delete_profile_id(self):
        with open(os.path.join(os.path.dirname(__file__), "data", "roster_kc.json"), "rt") as fp:
            srcdata = json.load(fp)
        rmgr = self._getRosterManager()
        recs = util.runCoroutine(rmgr.save(srcdata))
        self.assertEqual(len(recs), len(srcdata), "save returned record count differs")
        dcount = util.runCoroutine(rmgr.delete(profile_ids=[2562399]))
        self.assertEqual(dcount, 1, "delete returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(len(dbrecs), len(srcdata) - 1, "db record count differs")
        xdata = [_ for _ in srcdata if _["profile_id"] != 2562399]
        self.assertEqual(dbrecs, xdata, "db records differ")

    def test__getQueryModel_player_abbreviations_one(self):
        rmgr = self._getRosterManager()
        qm = rmgr._getQueryModel(player_abbreviations=["C.Wollam"])
        xconst = {"$and": [
            {"first_name": {"$regex": "^c.*", "$options": "i"}},
            {"last_name": {"$regex": "^wollam", "$options": "i"}}
        ]}
        self.assertEqual(qm.constraint, xconst)

    def test__getQueryModel_player_abbreviations_one_suffix(self):
        rmgr = self._getRosterManager()
        qm = rmgr._getQueryModel(player_abbreviations=["C.Wollam Jr."])
        xconst = {"$and": [
            {"first_name": {"$regex": "^c.*", "$options": "i"}},
            {"last_name": {"$regex": "^wollam( *jr)*", "$options": "i"}}
        ]}
        self.assertEqual(qm.constraint, xconst)

    def test__getQueryModel_player_abbreviations_two(self):
        rmgr = self._getRosterManager()
        qm = rmgr._getQueryModel(player_abbreviations=["C.Wollam", "M.King"])
        xconst = {"$or": [
            {"$and": [
                {"first_name": {"$regex": "^c.*", "$options": "i"}},
                {"last_name": {"$regex": "^wollam", "$options": "i"}}
            ]},
            {"$and": [
                {"first_name": {"$regex": "^m.*", "$options": "i"}},
                {"last_name": {"$regex": "^king", "$options": "i"}}
            ]}
        ]}
        self.assertEqual(qm.constraint, xconst)
 def setUp(self):
     self.entityName = "schedule"
     self.procEntityName = "schedule_process"
     self.entmgr = EntityManager()
class TestScheduleManagerFacade(unittest.TestCase):
    def setUp(self):
        self.entityName = "schedule"
        self.procEntityName = "schedule_process"
        self.entmgr = EntityManager()

    def tearDown(self):
        util.runCoroutine(self.entmgr.drop(self.entityName))
        util.runCoroutine(self.entmgr.drop(self.procEntityName))
        self.entmgr.dispose()

    def _getMockScheduleManager(self, scheduleData: List[dict]):
        apiClient = MockApiClient(scheduleData)
        self.datamgr = ScheduleManagerFacade(self.entmgr, apiClient)
        return self.datamgr

    def test_sync_initializes_collection(self):
        srcdata = []
        tddpath = os.path.join(os.path.dirname(__file__), "data")
        for fname in [
                "schedule_2017.json", "schedule_2018.json",
                "schedule_2019.json"
        ]:
            with open(os.path.join(tddpath, fname), "rt") as fp:
                srcdata.extend(json.load(fp))
        xreq = [{"season": 2017}, {"season": 2018}, {"season": 2019}]
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        recs = util.runCoroutine(smgr.sync())
        self.assertEqual(len(recs), len(srcdata),
                         "sync returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs, "db records differ")
        self.assertEqual(smgr._apiClient.getRequestedData(), xreq,
                         "api requests differ")

    def test_sync_req_unfinished_only_after_initialized_in_regseason(self):
        srcdata = []
        updata = []
        tddpath = os.path.join(os.path.dirname(__file__), "data")
        for fname in [
                "schedule_2017.json", "schedule_2018.json",
                "schedule_2019.json"
        ]:
            with open(os.path.join(tddpath, fname), "rt") as fp:
                data = json.load(fp)
                srcdata.extend(data)
                if fname == "schedule_2019.json":
                    updata = [rec for rec in data if not rec["finished"]]
        xreq = []
        for week in range(14, 18):
            xreq.append({
                "season": 2019,
                "season_type": "regular_season",
                "week": week
            })
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        recs1 = util.runCoroutine(smgr.sync())
        self.assertEqual(len(recs1), len(srcdata),
                         "sync1 returned record count differs")
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        recs2 = util.runCoroutine(smgr.sync())
        self.assertEqual(len(recs2), len(updata),
                         "sync2 returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs1, "db records differ")
        apireq = smgr._apiClient.getRequestedData()
        self.assertEqual(len(apireq), len(xreq), "api request lengths differ")
        self.assertEqual(apireq, xreq, "api requests differ")

    def test_sync_req_postseason_only_after_initialized_after_regseason(self):
        srcdata = []
        psdata = []
        tddpath = os.path.join(os.path.dirname(__file__), "data")
        for fname in [
                "schedule_2017.json", "schedule_2018.json",
                "schedule_2019.json"
        ]:
            with open(os.path.join(tddpath, fname), "rt") as fp:
                data = json.load(fp)
                srcdata.extend(data)
                if fname == "schedule_2018.json":
                    # use the 2018 postseason data as the 2019 postseason data
                    for d in [
                            r for r in data if r["season_type"] == "postseason"
                    ]:
                        ud = d.copy()
                        ud["finished"] = False
                        ud["season"] = 2019
                        ud["gsis_id"] = ud["gsis_id"].replace(
                            "2019", "2020", 1)
                        psdata.append(ud)
        for rec in srcdata:
            if not rec["finished"]:
                rec["finished"] = True
        xreq = []
        for week in range(1, 5):
            xreq.append({
                "season": 2019,
                "season_type": "postseason",
                "week": week
            })
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        recs1 = util.runCoroutine(smgr.sync())
        self.assertEqual(len(recs1), len(srcdata),
                         "sync1 returned record count differs")
        smgr = self._getMockScheduleManager(scheduleData=psdata)
        recs2 = util.runCoroutine(smgr.sync())
        self.assertEqual(len(recs2), len(psdata),
                         "sync2 returned record count differs")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        xdbrecs = recs1 + recs2
        self.assertEqual(len(dbrecs), len(xdbrecs), "db record lengths differ")
        self.assertEqual(dbrecs, xdbrecs, "db records differ")
        apireq = smgr._apiClient.getRequestedData()
        self.assertEqual(len(apireq), len(xreq), "api request lengths differ")
        self.assertEqual(apireq, xreq, "api requests differ")

    def test_save_adds_teams(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "schedule_2017.json"), "rt") as fp:
            srcdata = json.load(fp)
        d = srcdata[0]
        smgr = ScheduleManagerFacade(self.entmgr)
        recs = util.runCoroutine(smgr.save([d]))
        self.assertEqual(len(recs), 1, "returned record count differs")
        self.assertTrue("teams" in recs[0], "teams not added")
        dbrecs = util.runCoroutine(self.entmgr.find(self.entityName))
        self.assertEqual(dbrecs, recs, "db records differ")
        self.assertEqual(dbrecs[0]["teams"], ["MIA", "ATL"],
                         "teams value differs")

    def test_find_by_teams(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "schedule_2017.json"), "rt") as fp:
            srcdata = json.load(fp)
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        util.runCoroutine(smgr.sync())
        recs = util.runCoroutine(smgr.find(teams=["ATL"]))
        self.assertEqual(len(recs), 22, "ATL record count differs")
        recs = util.runCoroutine(smgr.find(teams=["ATL", "NE"]))
        self.assertEqual(len(recs), 44, "ATL, NE record count differs")

    def test_find_by_finished(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "schedule_2019.json"), "rt") as fp:
            srcdata = json.load(fp)
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        util.runCoroutine(smgr.sync())
        recs = util.runCoroutine(smgr.find(finished=True))
        self.assertEqual(len(recs), 32, "True record count differs")
        recs = util.runCoroutine(smgr.find(finished=False))
        self.assertEqual(len(recs), 8, "False record count differs")

    def test_find_by_season(self):
        srcdata = []
        tddpath = os.path.join(os.path.dirname(__file__), "data")
        for fname in [
                "schedule_2017.json", "schedule_2018.json",
                "schedule_2019.json"
        ]:
            with open(os.path.join(tddpath, fname), "rt") as fp:
                srcdata.extend(json.load(fp))
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        util.runCoroutine(smgr.sync())
        recs = util.runCoroutine(smgr.find(seasons=[2017]))
        self.assertEqual(len(recs), 44, "2017 record count differs")
        recs = util.runCoroutine(smgr.find(seasons=[2017, 2019]))
        self.assertEqual(len(recs), 84, "2017, 2019 record count differs")

    def test_find_by_season_type(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "schedule_2017.json"), "rt") as fp:
            srcdata = json.load(fp)
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        util.runCoroutine(smgr.sync())
        recs = util.runCoroutine(smgr.find(season_types=["regular_season"]))
        self.assertEqual(len(recs), 31, "regular_season record count differs")
        recs = util.runCoroutine(
            smgr.find(season_types=["regular_season", "postseason"]))
        self.assertEqual(len(recs), 36,
                         "regular_season, postseason record count differs")

    def test_find_by_season_type_week(self):
        with open(
                os.path.join(os.path.dirname(__file__), "data",
                             "schedule_2017.json"), "rt") as fp:
            srcdata = json.load(fp)
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        util.runCoroutine(smgr.sync())
        recs = util.runCoroutine(
            smgr.find(season_types=["regular_season"], weeks=[1]))
        self.assertEqual(len(recs), 2,
                         "regular_season week 1 record count differs")
        recs = util.runCoroutine(
            smgr.find(season_types=["postseason"], weeks=[2]))
        self.assertEqual(len(recs), 2,
                         "postseason week 2 record count differs")

    def test_find_by_last(self):
        srcdata = []
        tddpath = os.path.join(os.path.dirname(__file__), "data")
        for fname in [
                "schedule_2017.json", "schedule_2018.json",
                "schedule_2019.json"
        ]:
            with open(os.path.join(tddpath, fname), "rt") as fp:
                srcdata.extend(json.load(fp))
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        util.runCoroutine(smgr.sync())
        recs = util.runCoroutine(smgr.find(last=True))
        self.assertEqual(len(recs), 2, "record count differs")
        for rec in recs:
            self.assertEqual(rec["season"], 2019,
                             "{} season differs".format(rec["gsis_id"]))
            self.assertEqual(rec["season_type"], "regular_season",
                             "{} season_type differs".format(rec["gsis_id"]))
            self.assertEqual(rec["week"], 13,
                             "{} week differs".format(rec["gsis_id"]))

    def test_find_by_next(self):
        srcdata = []
        tddpath = os.path.join(os.path.dirname(__file__), "data")
        for fname in [
                "schedule_2017.json", "schedule_2018.json",
                "schedule_2019.json"
        ]:
            with open(os.path.join(tddpath, fname), "rt") as fp:
                srcdata.extend(json.load(fp))
        smgr = self._getMockScheduleManager(scheduleData=srcdata)
        util.runCoroutine(smgr.sync())
        recs = util.runCoroutine(smgr.find(next=True))
        self.assertEqual(len(recs), 2, "record count differs")
        for rec in recs:
            self.assertEqual(rec["season"], 2019,
                             "{} season differs".format(rec["gsis_id"]))
            self.assertEqual(rec["season_type"], "regular_season",
                             "{} season_type differs".format(rec["gsis_id"]))
            self.assertEqual(rec["week"], 14,
                             "{} week differs".format(rec["gsis_id"]))
Example #15
0
 def setUp(self):
     self.entityName = "team"
     self.entmgr = EntityManager()
     self.datamgr = TeamManagerFacade(self.entmgr)