def setUp(self): self.filename = "test_database.db" open(self.filename, "w").close() self.dom = SqlLiteDom(self.filename) self.dom.createDatabaseTables() self.dom.createBankTables() self.dom.createGameAccountMappingTable()
def testCreateLiveLeaderboard(self): realDom = SqlLiteDom("../infrastructure/actual_db_copy") leaderboard = analyzer.createLiveLeaderboard( realDom, "kills/timePlayed pilot.kills/kills ground.kills/ground.timePlayed", 100) print(leaderboard)
class TestBattalion(unittest.TestCase): def setUp(self): self.filename = "test_database.db" open(self.filename, "w").close() self.dom = SqlLiteDom(self.filename) self.dom.createBattalionTables() self.dom.createDatabaseTables() def tearDown(self): os.remove(self.filename) def testCreateBattalion(self): battalion.createBattalion(self.dom, "jacob", "ugly") battalions = battalion.getBattalions(self.dom) self.assertEquals(battalions[0][0], "ugly") permission = battalion.getUserPermission(self.dom, "jacob", "ugly") self.assertEquals(permission[0][0], "GENERAL") userBattalions = battalion.getUserBattalionPermissions(self.dom, "jacob") self.assertEquals(userBattalions[0], ("jacob", "ugly", "GENERAL"))
def testRealGetJoinedStat(self): realDom = SqlLiteDom("../infrastructure/actual_db_copy") joinedStat = realDom.getJoinedStat(1, 2) creatifStatLine = None parizvalStatLine = None for statLine in joinedStat: if statLine[0] == "Creatif_Craxy": creatifStatLine = statLine elif statLine[0] == "ParzivalVii": parizvalStatLine = statLine self.assertTrue(creatifStatLine != None) self.assertTrue(parizvalStatLine != None) creatifKills = analyzer.getStatDiffFromLine(creatifStatLine, "kills", "overview") parizvalKills = analyzer.getStatDiffFromLine(parizvalStatLine, "kills", "overview") self.assertEquals(68, creatifKills) self.assertEquals(172, parizvalKills) sqlTemplate = "SELECT * FROM stats where username='******' and key = %s" newStats = realDom.performQuery(sqlTemplate % ("Creatif_Craxy", 2)) prevStats = realDom.performQuery(sqlTemplate % ("Creatif_Craxy", 1)) newStatJson = json.loads(newStats[0][2]) prevStatJson = json.loads(prevStats[0][2]) newKills = newStatJson['data']['segments'][0]['stats']['kills'][ 'value'] prevKills = prevStatJson['data']['segments'][0]['stats']['kills'][ 'value'] prevPlatformId = prevStatJson['data']['platformInfo'][ 'platformUserIdentifier'] newPlatformId = newStatJson['data']['platformInfo'][ 'platformUserIdentifier'] prevLastUpdated = prevStatJson['data']['metadata']['lastUpdated'][ 'value'] newLastUpdated = newStatJson['data']['metadata']['lastUpdated'][ 'value'] self.assertEquals(creatifKills, newKills - prevKills) self.assertEquals(newPlatformId, 'creatif_craxy') self.assertEquals(prevPlatformId, newPlatformId)
class TestBank(unittest.TestCase): def setUp(self): self.filename = "test_database.db" open(self.filename, "w").close() self.dom = SqlLiteDom(self.filename) self.dom.createBankTables() def tearDown(self): os.remove(self.filename) def testAward(self): self.dom.createAccount("jacob") bank.award(self.dom, "jacob", 100) balance = bank.balance(self.dom, "jacob") self.assertEquals(balance, 100) def testTransfer(self): self.dom.createAccount("jacob") self.dom.createAccount("noah") bank.award(self.dom, "jacob", 100) bank.transfer(self.dom, "jacob", "noah", 25) self.assertTrue(75, bank.balance(self.dom, "jacob")) self.assertTrue(25, bank.balance(self.dom, "noah"))
class TestDomOperations(unittest.TestCase): defaultUsername = '******' defaultBattalion = 'ugly' #TODO add alternate data #TODO map all returns to entry def setUp(self): self.filename = "test_database.db" open(self.filename, "w").close() self.dom = SqlLiteDom(self.filename) def tearDown(self): os.remove(self.filename) def testCreateConnection(self): conn = self.dom.createConnection() self.assertTrue(conn.cursor()) conn.close() def testKeyOperations(self): self.dom.createDatabaseTables() key = self.dom.getKey() self.assertEquals(None, key) key = self.dom.incremementKey() self.assertEquals(0, key) key = self.dom.getKey() self.assertEquals(0, key) index = self.dom.getIndex(key) self.assertTrue(index[0][1] > 10) def testRegisterChannel(self): self.dom.createDatabaseTables() self.dom.registerChannel(1616171771178818181818181881) self.dom.registerChannel(171717717) channels = self.dom.getChannels() self.assertEquals(2, len(channels)) self.dom.clearChannels() channels = self.dom.getChannels() self.assertEquals(0, len(channels)) def testEnlistUser(self): self.dom.createDatabaseTables() self.dom.enlistUser(self.defaultUsername) users = self.dom.getUsers() self.assertEquals(1, len(users)) self.assertEquals(self.defaultUsername, users[0][0]) def testDischargeUser(self): self.dom.createDatabaseTables() self.dom.enlistUser(self.defaultUsername) self.dom.dischargeUser(self.defaultUsername) users = self.dom.getUsers() self.assertEquals(0, len(users)) def testGetJoinedStat(self): self.dom.createDatabaseTables() stat1a = {'data':{'segments':[{'stats':{'metric':{'value':2}}}]}} #stat1b = {'data':{'segments':[{'stats':{'metric':{'value':1}}}]}} stat2a = {'data':{'segments':[{'stats':{'metric':{'value':3}}}]}} stat2b = {'data':{'segments':[{'stats':{'metric':{'value':5}}}]}} stat3a = {'data':{'segments':[{'stats':{'metric':{'value':8}}}]}} stat3b = {'data':{'segments':[{'stats':{'metric':{'value':8}}}]}} self.dom.loadStat('usera',0, json.dumps(stat1a)) #self.dom.loadStat('userb',0, json.dumps(stat1b)) self.dom.loadStat('usera',1, json.dumps(stat2a)) self.dom.loadStat('userb',1, json.dumps(stat2b)) self.dom.loadStat('usera',2, json.dumps(stat3a)) self.dom.loadStat('userb',2, json.dumps(stat3b)) joinedStat = self.dom.getFriendlyJoinedStat(0, 1) self.assertEquals(2, len(joinedStat)) def testGetFriendlyJoinedStat(self): self.dom.createDatabaseTables() stat1a = {'data':{'segments':[{'stats':{'metric':{'value':2}}}]}} stat2a = {'data':{'segments':[{'stats':{'metric':{'value':3}}}]}} stat2b = {'data':{'segments':[{'stats':{'metric':{'value':5}}}]}} stat3a = {'data':{'segments':[{'stats':{'metric':{'value':8}}}]}} stat3b = {'data':{'segments':[{'stats':{'metric':{'value':8}}}]}} self.dom.loadStat('usera',0, json.dumps(stat1a)) self.dom.loadStat('usera',1, json.dumps(stat2a)) self.dom.loadStat('userb',1, json.dumps(stat2b)) self.dom.loadStat('usera',2, json.dumps(stat3a)) self.dom.loadStat('userb',2, json.dumps(stat3b)) joinedStat = self.dom.getFriendlyJoinedStat(0, 1) self.assertEquals(2, len(joinedStat)) self.assertEquals(0, joinedStat[0][3]) self.assertEquals(1, joinedStat[1][3]) #### BANKING TESTS def testGetNoAccount(self): self.dom.createBankTables() account = self.dom.getAccount("user") self.assertEquals(len(account), 0) def testGetAccount(self): self.dom.createBankTables() self.dom.createAccount("user") account = self.dom.getAccount("user") self.assertEquals(len(account), 1) self.assertEquals(account[0][0], "user") self.assertEquals(account[0][1], 0) def testDeltaBalance(self): self.dom.createBankTables() self.dom.createAccount("user") self.dom.deltaBalance("user", 50) account = self.dom.getAccount("user") self.assertEqual(len(account), 1) self.assertEquals(account[0][0], "user") self.assertEquals(account[0][1], 50) self.dom.deltaBalance("user", -30) self.assertTrue(len(account), 1) account = self.dom.getAccount("user") self.assertEquals(account[0][1], 20) def testCreateDuplicateAccountFail(self): self.dom.createBankTables() self.dom.createAccount("user") self.assertRaises( sqlite3.IntegrityError, self.dom.createAccount, "user" ) def createAndDropTable(self): self.dom.createBankTables() self.dom.createAccount("user") self.dom.dropBankTables() self.dom.createBankTables() account = self.dom.getAccount("user") self.assertEquals(len(account), 0) #### CONSCRIPTION TESTS # def testConscriptUser(self): self.dom.createGameAccountMappingTable() self.dom.conscriptUser("jacob", "psn", "creatif_craxy") account = self.dom.getAccountForPlatformUsername("psn", "creatif_craxy") self.assertEquals("jacob", account) def testConscriptUser(self): self.dom.createGameAccountMappingTable() self.dom.conscriptUser("jacob", "psn", "creatif_craxy") self.assertRaises( sqlite3.IntegrityError, self.dom.conscriptUser, "some_schmuck", "psn", "creatif_craxy" ) def testGetAccountForPlatformUserName(self): self.dom.createGameAccountMappingTable() self.dom.conscriptUser("jacob", "psn", "creatif_craxy") accountMapping = self.dom.getAccountForPlatformUsername("psn", "creatif_craxy") self.assertEquals("jacob", accountMapping) def testGetAccountForPlatformUserName(self): self.dom.createGameAccountMappingTable() accountMapping = self.dom.getAccountForPlatformUsername("psn", "creatif_craxy") self.assertEquals(None, accountMapping) def testCreateAndDropTable(self): self.dom.createGameAccountMappingTable() self.dom.conscriptUser("jacob", "psn", "creatif_craxy") accountMapping = self.dom.getAccountForPlatformUsername("psn", "creatif_craxy") self.dom.dropMappingTable() self.dom.createGameAccountMappingTable() accountMapping = self.dom.getAccountForPlatformUsername("psn", "creatif_craxy") self.assertEquals(None, accountMapping) def testBattalionOperations(self): self.dom.createBattalionTables() self.dom.createBattalion("UGLY") battalions = self.dom.getBattalions() self.assertEquals(battalions[0][0], "UGLY") self.dom.setUserPermissionOnBattalion("jacob", "UGLY", "ADMIN") permissions = self.dom.getUserBattalionPermission("jacob", "COMMANDER") self.assertEquals(permissions[0][0], "COMMANDER")
class TestHr(unittest.TestCase): def setUp(self): self.filename = "test_database.db" open(self.filename, "w").close() self.dom = SqlLiteDom(self.filename) self.dom.createDatabaseTables() self.dom.createBankTables() self.dom.createGameAccountMappingTable() def tearDown(self): os.remove(self.filename) def testProcessPerformace(self): hr.conscript(self.dom, "jacob", "psn", "creatif_craxy") stat0a = { 'data': { 'segments': [{ 'stats': { 'wins': { 'value': 1 }, "kills": { 'value': 0 } } }] } } stat0b = { 'data': { 'segments': [{ 'stats': { 'wins': { 'value': 5 }, "kills": { 'value': 100 } } }] } } self.dom.loadStat('creatif_craxy', 0, json.dumps(stat0a)) self.dom.loadStat('creatif_craxy', 1, json.dumps(stat0b)) hr.processPerformance(self.dom, 0, 1) self.assertEquals(self.dom.balance("jacob"), 5) def testReport(self): hr.conscript(self.dom, "jacob", "psn", "creatif_craxy") stat0a = { 'data': { 'segments': [{ 'stats': { 'wins': { 'value': 1 }, "kills": { 'value': 0 } } }] } } stat0b = { 'data': { 'segments': [{ 'stats': { 'wins': { 'value': 5 }, "kills": { 'value': 100 } } }] } } self.dom.loadStat('creatif_craxy', 0, json.dumps(stat0a)) self.dom.loadStat('creatif_craxy', 1, json.dumps(stat0b)) performanceInfo = hr.processPerformance(self.dom, 0, 1) self.assertEquals(self.dom.balance("jacob"), 5) report = hr.generateReports(performanceInfo, None) print(report) def testComplexPerformace(self): hr.conscript(self.dom, "jacob", "psn", "creatif_craxy") hr.conscript(self.dom, "noah", "psn", "ugly_noah") stat0a = { 'data': { 'segments': [{ 'stats': { 'wins': { 'value': 1 }, "kills": { 'value': 0 } } }] } } stat0b = { 'data': { 'segments': [{ 'stats': { 'wins': { 'value': 5 }, "kills": { 'value': 100 } } }] } } self.dom.loadStat('creatif_craxy', 0, json.dumps(stat0a)) self.dom.loadStat('creatif_craxy', 1, json.dumps(stat0b)) self.dom.loadStat('ugly_noah', 0, json.dumps(stat0a)) self.dom.loadStat('ugly_noah', 1, json.dumps(stat0b)) hr.processPerformance(self.dom, 0, 1) self.assertEquals(self.dom.balance("jacob"), 5) self.assertEquals(self.dom.balance("noah"), 5) def testAwardTokensToGameAccounts(self): hr.conscript(self.dom, "jacob", "psn", "creatif_craxy") hr.conscript(self.dom, "jacob", "psn", "my_alt") hr.conscript(self.dom, "noah", "psn", "uglynoah") table = [["creatif_craxy", 10], ["my_alt", 3], ["uglynoah", 8]] hr.awardTokensToGameAccounts(self.dom, table) self.assertEquals(self.dom.balance("jacob"), 13) self.assertEquals(self.dom.balance("noah"), 8) def testAwardTokensToGameAccounts(self): hr.conscript(self.dom, "jacob", "psn", "creatif_craxy") hr.conscript(self.dom, "jacob", "psn", "my_alt") hr.conscript(self.dom, "noah", "psn", "uglynoah") table = [["creatif_craxy", 10, 0], ["my_alt", 3, 0], ["uglynoah", 8, 0]] hr.awardTokensToGameAccounts(self.dom, table) self.assertEquals(self.dom.balance("jacob"), 13) self.assertEquals(self.dom.balance("noah"), 8) def testConscript(self): hr.conscript(self.dom, "jacob", "psn", "creatif_craxy") print(self.dom.getUsers()) self.assertTrue(self.dom.userExists("creatif_craxy")) self.assertTrue(self.dom.hasAccount("jacob")) account = self.dom.getAccountForPlatformUsername( "psn", "creatif_craxy") self.assertEquals(account, "jacob")
def getUserBattalionPermissions(dom: SqlLiteDom, actor): return dom.getUserBattalions(actor)
def createBattalion(dom: SqlLiteDom, actor, battalionName): dom.createBattalion(battalionName) dom.setUserPermissionOnBattalion(actor, battalionName, "GENERAL")
#!/usr/bin/python3 from discord.ext.commands import Bot from discord.ext import commands from infrastructure import env_variables from infrastructure.db import SqlLiteDom from analyzertools import analyzer, loader from economy import bank, hr from botcogs.analyzer_cog import AnalyzerCog client = Bot(description="Very Cool Bot Made by Jacob/Creatif_Craxy. Type \"!help analyze\" for more information", command_prefix="!", ) filename = env_variables.dbFilename() dom = SqlLiteDom(filename) client.add_cog(AnalyzerCog(client, dom)) @client.event async def on_ready(): # dom.getUsers() print('We have logged in as {0.user}'.format(client)) ### PERMISSIONS CHECKS ### async def hasPermissions(ctx): return ctx.message.author.id == 693962849717846147 or ctx.message.author.guild_permissions.administrator async def isSysAdmin(ctx): return ctx.message.author.id == 693962849717846147
def testRealMessage(self): realDom = SqlLiteDom("../infrastructure/actual_db_copy") report = analyzer.craftLastMessage(realDom) print(report)
def enlist(dom: SqlLiteDom, actor, battalionName, platformId): permission = dom.getUserBattalionPermission(actor, battalionName) if len(permission) > 1 and permission[0][0] == "GENERAL" or permission[0][ 0] == "OFFICER": dom.enlistUser(battalionName, platformId)
class TestTaskOperations(unittest.TestCase): def setUp(self): self.filename = "test_database.db" open(self.filename, "w").close() self.dom = SqlLiteDom(self.filename) self.dom.createDatabaseTables() self.dom.enlistUser('Creatif_Craxy') def tearDown(self): os.remove(self.filename) def testStoreAndIncrement(self): loader.storeAndIncrement(self.dom) loader.storeAndIncrement(self.dom) joinedStat = self.dom.getFriendlyJoinedStat(0, 1) self.assertEquals(1, len(joinedStat)) self.assertEquals(4, len(joinedStat[0])) def testStoreData(self): loader.storeData(self.dom, 0) loader.storeData(self.dom, 1) joinedStat = self.dom.getFriendlyJoinedStat(0, 1) self.assertEquals(1, len(joinedStat)) self.assertEquals(4, len(joinedStat[0])) def testDuplicateStores(self): loader.storeData(self.dom, 0) loader.storeData(self.dom, 1) self.assertRaises(sqlite3.IntegrityError, loader.storeData, self.dom, 1) def testGetTotalForPeriod(self): stat1a = {'data': {'segments': [{'stats': {'metric': {'value': 2}}}]}} stat1b = {'data': {'segments': [{'stats': {'metric': {'value': 1}}}]}} stat2a = {'data': {'segments': [{'stats': {'metric': {'value': 3}}}]}} stat2b = {'data': {'segments': [{'stats': {'metric': {'value': 5}}}]}} self.dom.loadStat('usera', 0, json.dumps(stat1a)) self.dom.loadStat('userb', 0, json.dumps(stat1b)) self.dom.loadStat('usera', 1, json.dumps(stat2a)) self.dom.loadStat('userb', 1, json.dumps(stat2b)) joinedStat = self.dom.getFriendlyJoinedStat(0, 1) periodTotal = analyzer.analyzeStatForPeriod(joinedStat, 'metric') self.assertEquals(5, periodTotal[2]) self.assertEquals(4, periodTotal[1]) self.assertEquals("userb", periodTotal[0]) def testGetTotalForPeriodMissingData(self): stat1a = {'data': {'segments': [{'stats': {'metric': {'value': 2}}}]}} stat2a = {'data': {'segments': [{'stats': {'metric': {'value': 3}}}]}} stat2b = {'data': {'segments': [{'stats': {'metric': {'value': 5}}}]}} self.dom.loadStat('usera', 0, json.dumps(stat1a)) self.dom.loadStat('usera', 1, json.dumps(stat2a)) self.dom.loadStat('userb', 1, json.dumps(stat2b)) joinedStat = self.dom.getFriendlyJoinedStat(0, 1) periodTotal = analyzer.analyzeStatForPeriod(joinedStat, 'metric') self.assertEquals(1, periodTotal[2]) self.assertEquals(1, periodTotal[1]) self.assertEquals("usera", periodTotal[0]) def testGetTotalForPeriodNoData(self): joinedStat = self.dom.getFriendlyJoinedStat(0, 1) periodTotal = analyzer.analyzeStatForPeriod(joinedStat, 'metric') self.assertEquals(0, periodTotal[2]) self.assertEquals(-1, periodTotal[1]) self.assertEquals("nobody", periodTotal[0]) def testCraftMessage(self): loader.storeAndIncrement(self.dom) loader.storeAndIncrement(self.dom) print(analyzer.craftMessage(self.dom, 0, 1)) def testRealMessage(self): realDom = SqlLiteDom("../infrastructure/actual_db_copy") report = analyzer.craftLastMessage(realDom) print(report) def testCreateLiveLeaderboard(self): realDom = SqlLiteDom("../infrastructure/actual_db_copy") leaderboard = analyzer.createLiveLeaderboard( realDom, "kills/timePlayed pilot.kills/kills ground.kills/ground.timePlayed", 100) print(leaderboard) def testRealGetJoinedStat(self): realDom = SqlLiteDom("../infrastructure/actual_db_copy") joinedStat = realDom.getJoinedStat(1, 2) creatifStatLine = None parizvalStatLine = None for statLine in joinedStat: if statLine[0] == "Creatif_Craxy": creatifStatLine = statLine elif statLine[0] == "ParzivalVii": parizvalStatLine = statLine self.assertTrue(creatifStatLine != None) self.assertTrue(parizvalStatLine != None) creatifKills = analyzer.getStatDiffFromLine(creatifStatLine, "kills", "overview") parizvalKills = analyzer.getStatDiffFromLine(parizvalStatLine, "kills", "overview") self.assertEquals(68, creatifKills) self.assertEquals(172, parizvalKills) sqlTemplate = "SELECT * FROM stats where username='******' and key = %s" newStats = realDom.performQuery(sqlTemplate % ("Creatif_Craxy", 2)) prevStats = realDom.performQuery(sqlTemplate % ("Creatif_Craxy", 1)) newStatJson = json.loads(newStats[0][2]) prevStatJson = json.loads(prevStats[0][2]) newKills = newStatJson['data']['segments'][0]['stats']['kills'][ 'value'] prevKills = prevStatJson['data']['segments'][0]['stats']['kills'][ 'value'] prevPlatformId = prevStatJson['data']['platformInfo'][ 'platformUserIdentifier'] newPlatformId = newStatJson['data']['platformInfo'][ 'platformUserIdentifier'] prevLastUpdated = prevStatJson['data']['metadata']['lastUpdated'][ 'value'] newLastUpdated = newStatJson['data']['metadata']['lastUpdated'][ 'value'] self.assertEquals(creatifKills, newKills - prevKills) self.assertEquals(newPlatformId, 'creatif_craxy') self.assertEquals(prevPlatformId, newPlatformId) def trackUpdates(self): query = analyzer.queryBfTracker('Creatif_Craxy') intialKills = query['data']['segments'][0]['stats']['kills']['value'] initialTime = query['data']['segments'][0]['stats']['timePlayed'][ 'value'] killTotal = intialKills timeTotal = initialTime for i in range(2000): query = analyzer.queryBfTracker('Creatif_Craxy') updatedKills = query['data']['segments'][0]['stats']['kills'][ 'value'] updatedTime = query['data']['segments'][0]['stats']['timePlayed'][ 'value'] killDiff = updatedKills - killTotal timeDiff = updatedTime - timeTotal totalKillDiff = updatedKills - intialKills curTime = curTime = time.time() formattedCurTime = timezone('US/Pacific').localize( datetime.datetime.fromtimestamp(curTime)).astimezone( timezone('US/Pacific')).strftime("%m/%d/%Y, %H:%M:%S") formattedTimeDiff = datetime.timedelta(seconds=timeDiff) formattedTotalTimePlayed = datetime.timedelta(seconds=timeTotal) lastGameMap = analyzer.queryLastGame( )['data']['reports'][0]['mapKey'] lastGameTimestamp = analyzer.queryLastGame( )['data']['reports'][0]['timestamp'] formattedLastGameTime = timezone('US/Pacific').localize( datetime.datetime.fromtimestamp(lastGameTimestamp)).astimezone( timezone('US/Pacific')).strftime("%m/%d/%Y, %H:%M:%S") printedStatement = """STATS FOR TIME: %s. KILL TOTAL: %s TIME TOTAL %s \nKIll DIFF: %s TIME DIFF: %s""" % ( formattedCurTime, killTotal, formattedTotalTimePlayed, killDiff, formattedTimeDiff) print(printedStatement) print("TOTAL KILL DIFF %s" % totalKillDiff) print('LAST GAME: %s PLAYED AT: %s\n' % (lastGameMap, formattedLastGameTime)) killTotal = updatedKills timeTotal = updatedTime time.sleep(20)
def setUp(self): self.filename = "test_database.db" open(self.filename, "w").close() self.dom = SqlLiteDom(self.filename) self.dom.createDatabaseTables() self.dom.enlistUser('Creatif_Craxy')
def setUp(self): self.filename = "test_database.db" open(self.filename, "w").close() self.dom = SqlLiteDom(self.filename) self.dom.createBattalionTables() self.dom.createDatabaseTables()
def setUp(self): self.filename = "test_database.db" open(self.filename, "w").close() self.dom = SqlLiteDom(self.filename)
def getUserPermission(dom: SqlLiteDom, actor, battalionName): return dom.getUserBattalionPermission(actor, battalionName)
def makeGeneral(dom: SqlLiteDom, actor, battalionName, userId): permission = dom.getUserBattalionPermission(actor, battalionName) if len(permission) > 1 and permission[0][0] == "GENERAL": dom.setUserPermissionOnBattalion(userId, battalionName, "GENERAL")
def getBattalions(dom: SqlLiteDom): return dom.getBattalions()