This repository has been archived by the owner on Jul 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtest.py
863 lines (716 loc) · 29.6 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
#!/usr/bin/env python3
import json
import logging
import os
import os.path
import sys
import time
import unittest
from unittest.mock import MagicMock
from unittest.mock import call
import uuid
import praw
from praw.config import Config
import prawcore
import requests
import scrape
# I didn't know this before creating the test
hsbot = __import__("hearthscan-bot")
import commentDB
import credentials
import formatter
from cardDB import CardDB
from constants import Constants
from helper import HSHelper
from helper import SpellChecker
from praww import RedditBot
from praww import _SeenDB
# start with 'test.py online' to start slow tests requiring internet and working credentials
SKIP_INTERNET_TESTS = len(sys.argv) < 2 or sys.argv[1] != "online"
def removeFile(path):
"""error free file delete"""
if os.path.isfile(path):
os.remove(path)
class TempJson():
"""context aware, self deleting json file creator"""
def __init__(self, obj):
self.obj = obj
self.file = str(uuid.uuid4()) + '.json'
def __enter__(self):
with open(self.file, "w", newline="\n") as f:
json.dump(self.obj, f, sort_keys=True, indent=2, separators=(',', ':'))
return self.file
def __exit__(self, type, value, traceback):
removeFile(self.file)
class TempFile():
"""context aware, self deleting file creator"""
def __init__(self, suffix):
self.file = str(uuid.uuid4()) + '.' + suffix
def __enter__(self):
return self.file
def __exit__(self, type, value, traceback):
removeFile(self.file)
class TestScrape(unittest.TestCase):
"""scrape.py"""
def test_camelCase(self):
self.assertEqual(scrape.camelCase("SPELL"), "Spell")
self.assertEqual(scrape.camelCase("HERO_POWER"), "Hero Power")
self.assertEqual(scrape.camelCase(""), None)
self.assertEqual(scrape.camelCase(None), None)
# @unittest.skipIf(SKIP_INTERNET_TESTS, "requires internet (and is slow)")
def test_hearthhead(self):
with requests.Session() as s:
self.assertEqual(scrape.getHTDId('Quick Shot', 'Spell', s),
'quick-shot')
self.assertEqual(scrape.getHTDId('Undercity Valiant',
'Minion', s), 'undercity-valiant')
self.assertEqual(scrape.getHTDId('Gorehowl', 'Weapon', s),
'gorehowl')
self.assertEqual(scrape.getHTDId('V-07-TR-0N',
'Minion', s), 'v-07-tr-0n')
self.assertEqual(scrape.getHTDId("Al'Akir the Windlord",
'Minion', s), 'alakir-the-windlord')
@unittest.skipIf(SKIP_INTERNET_TESTS, "requires internet (and is slow)")
def test_Hearthpwn(self):
with requests.Session() as s:
self.assertEqual(scrape.getHearthpwnIdAndUrl('Quick Shot',
'Blackrock Mountain', 'Spell', False, s),
(14459, 'https://media-hearth.cursecdn.com/avatars/328/302/14459.png'))
self.assertEqual(scrape.getHearthpwnIdAndUrl('Upgrade!',
'Classic', 'Spell', False, s),
(638, 'https://media-hearth.cursecdn.com/avatars/330/899/638.png'))
@unittest.skipIf(SKIP_INTERNET_TESTS, "requires internet (and is slow)")
def test_full(self):
expected = {
'Quick Shot': {
'type': 'Spell',
'hpwn': 14459,
'cdn': 'https://media-hearth.cursecdn.com/avatars/328/302/14459.png',
'desc': 'Deal 3 damage. If your hand is empty, draw a card.',
'hp': None,
'class': 'Hunter',
'subType': None,
'set': 'Blackrock Mountain',
'rarity': 'Common',
'atk': None,
'head': 'quick-shot',
'name': 'Quick Shot',
'cost': 2
}
}
# scrape just one card
cards = {
"ignoredId" : {
'type': 'Spell',
'desc': 'Deal 3 damage. If your hand is empty, draw a card.',
'hp': None,
'class': 'Hunter',
'subType': None,
'set': 'Blackrock Mountain',
'rarity': 'Common',
'atk': None,
'name': 'Quick Shot',
'cost': 2
}
}
# this file is created to cache results
removeFile('data/07 Blackrock Mountain.json')
scraped = scrape.loadSets(cards, ['07'])
removeFile('data/07 Blackrock Mountain.json')
self.assertEqual(scraped, expected)
@unittest.skipIf(SKIP_INTERNET_TESTS, "requires internet (and is slow)")
def test_full_tokens(self):
self.maxDiff = None
expected = {
'Quick Shot': {
'type': 'Spell',
'hpwn': 14459,
'cdn': 'https://media-hearth.cursecdn.com/avatars/328/302/14459.png',
'desc': 'Deal 3 damage. If your hand is empty, draw a card.',
'hp': None,
'class': 'Hunter',
'subType': None,
'set': 'Blackrock Mountain',
'rarity': 'Common',
'atk': None,
'head': 'quick-shot',
'name': 'Quick Shot',
'cost': 2
}
}
# scrape just one card
wantedtokens = {
"Quick Shot": {
"id" : "BRM_013",
"hpwn": 14459
}
}
tokens = {
"BRM_013" : {
'type': 'Spell',
'desc': 'Deal 3 damage. If your hand is empty, draw a card.',
'hp': None,
'class': 'Hunter',
'subType': None,
'set': 'Blackrock Mountain',
'rarity': 'Common',
'atk': None,
'name': 'Quick Shot',
'cost': 2
}
}
self.assertEqual(scrape.loadTokens(tokens, wantedtokens), expected)
@unittest.skipIf(SKIP_INTERNET_TESTS, "requires internet (and is slow)")
def test_JsonCards_loadFixer(self):
cards, tokens = scrape.loadJsonCards()
# description
self.assertEqual(cards['LOE_079']['desc'],
"Battlecry: Shuffle the 'Map to the Golden Monkey' into your deck.")
self.assertEqual(cards['GVG_085']['desc'], "Taunt Divine Shield")
self.assertEqual(cards['GVG_012']['desc'][:16], "Restore 3 Health")
self.assertEqual(cards['EX1_279']['desc'], "Deal 10 damage.")
self.assertEqual(cards['BRM_013']['desc'],
"Deal 3 damage. If your hand is empty, draw a card.")
self.assertEqual(cards['EX1_298']['desc'][:13], "Can't attack.")
self.assertEqual(cards['CFM_902']['desc'],
"Battlecry and Deathrattle: Summon a Jade Golem.")
# multi class
self.assertEqual(cards['CFM_902']['class'], "Lotus (DRS)")
@unittest.skipIf(SKIP_INTERNET_TESTS, "requires internet (and is slow)")
def test_single(self):
expected = {
'type': 'Spell',
'hpwn': 14459,
'cdn': 'https://media-hearth.cursecdn.com/avatars/328/302/14459.png',
'desc': 'Deal 3 damage.If your hand is empty, draw a card.',
'hp': None,
'class': 'Hunter',
'subType': None,
'set': 'Blackrock Mountain',
'rarity': 'Common',
'atk': None,
'head': 'quick-shot',
'name': 'Quick Shot',
'cost': 2
}
name, card = scrape.parseSingle(14459)
self.assertEqual(card, expected)
class TestConst(unittest.TestCase):
"""constants.py constants.json"""
def test_ScrapeConstSetLength(self):
# easy to miss one when a new set is added
c = Constants()
self.assertEqual(len(scrape.jsonToCCSet), len(c.sets),
'okay to fail during spoiler season')
self.assertEqual(len(scrape.setids), len(c.sets))
self.assertEqual(len(scrape.setNameIds), len(c.sets))
def test_SpecialReplacements(self):
constantJson = {
'sets' : { },
'specials' : {
"dream cards" : ["dream", "emeralddrake", "laughingsister",
"nightmare", "ysera awakens"]
},
'alternative_names' : { }
}
with TempJson(constantJson) as json:
c = Constants(json)
# tests replace
replaced = c.replaceSpecial(["111", "dreamcards", "333", "444"])
self.assertEqual(replaced, ["111",
"dream",
"emeralddrake",
"laughingsister",
"nightmare",
"yseraawakens",
"333",
"444"])
def test_AlternativeReplacements(self):
constantJson = {
'sets' : { },
'specials' : { },
'alternative_names' : {
'carda' : 'ca',
'card b' : ['cb', 'cb b']
}
}
with TempJson(constantJson) as json:
c = Constants(json)
self.assertEqual(c.translateAlt("ca"), "carda")
self.assertEqual(c.translateAlt("cb"), "cardb")
self.assertEqual(c.translateAlt("cc"), "cc")
class TestCommentDB(unittest.TestCase):
"""commentDB.py"""
testDBName = "test.db"
def test_CreateFindFailParent(self):
removeFile(self.testDBName)
db = commentDB.DB(self.testDBName)
self.assertFalse(db.exists("abc", ["a card"]))
# inserted on exists
self.assertTrue(db.exists("abc", ["a card"]))
self.assertFalse(db.exists("abc", ["b card"]))
self.assertTrue(db.exists("abc", ["a card", "b card"]))
self.assertFalse(db.exists("abc", ["a card", "b card", "c card"]))
self.assertFalse(db.exists("123", ["a card"]))
db.close()
removeFile(self.testDBName)
class TestPRAWW(unittest.TestCase):
"""praww.py"""
@unittest.skipIf(SKIP_INTERNET_TESTS, "requires internet (and is slow)")
def test_RedditAuth(self):
# will fail for missing/bad praw.ini
with TempFile('db') as seenDB:
RedditBot(subreddits=[], newLimit=1, sleep=0, connectAttempts=1,
dbName=seenDB) \
.run(lambda: removeFile(RedditBot.LOCK_FILE))
@unittest.skipIf(SKIP_INTERNET_TESTS, "requires internet (and is slow)")
def test_RedditAuthFail(self):
def raiseError():
raise Exception('unexpected')
try:
# backup existing praw ini, create our own
if os.path.isfile('praw.ini'):
os.rename('praw.ini', '_praw.ini')
with open('praw.ini', 'w', newline="\n") as f:
f.write('[testbot]\n')
f.write('check_for_updates=false\n')
f.write('client_id=badid\n')
f.write('client_secret=badsecret\n')
f.write('refresh_token=badtoken\n')
f.write('user_agent=praw:hearthscan-test:1.0 (by /u/b0ne123)')
Config.CONFIG = None
with self.assertRaises(prawcore.exceptions.ResponseException), \
TempFile('db') as seenDB:
RedditBot(subreddits=[], newLimit=1, sleep=0, connectAttempts=1,
iniSite='testbot', dbName=seenDB) \
.run(raiseError)
finally:
removeFile('praw.ini')
if os.path.isfile('_praw.ini'):
os.rename('_praw.ini', 'praw.ini')
def test_seenDB(self):
with TempFile('db') as dbfile:
db = _SeenDB(dbfile)
class Thing():
fullname = "t1_thingid"
thing = Thing()
self.assertFalse(db.isSeen(thing))
self.assertTrue(db.isSeen(thing))
db.cleanup(secondsOld = 0)
self.assertFalse(db.isSeen(thing))
self.assertTrue(db.isSeen(thing))
db.close()
class TestCardDB(unittest.TestCase):
"""cardDB.py"""
def test_CleanName(self):
self.assertEqual(CardDB.cleanName('Ab: 1c'), 'abc')
def test_CardDB(self):
cardDict = {
'Quick Shot': {
'type': 'Spell',
'hpwn': 14459,
'cdn': 'https://media-Hearth.cursecdn.com/14459.png',
'desc': 'Deal 3 damage. Draw a card.',
'hp': 1,
'class': 'Hunter',
'subType': 'Mech',
'set': 'Basic',
'rarity': 'Common',
'atk': 3,
'head': 'quick-shot',
'name': 'Quick Shot',
'cost': 2
}
}
constantDict = {
'sets' : { '01' : {'name' : 'Basic'} },
'specials' : { },
'alternative_names' : { }
}
with TempJson(constantDict) as constJson, \
TempJson(cardDict) as cardJson, \
TempJson({}) as emptyJson:
c = Constants(constJson)
db = CardDB(constants=c, cardJSON=cardJson, duelsJSON=emptyJson, vanillaJSON=emptyJson, tokenJSON=emptyJson, tempJSON=emptyJson)
self.assertEqual(db.cardNames(), ['quickshot'])
self.assertEqual(db.tokens, [])
self.assertTrue('quickshot' in db)
self.assertFalse('slowshot' in db)
self.assertFalse('d!quickshot' in db)
self.assertFalse('c!quickshot' in db)
self.assertTrue('Quick Shot' in db['quickshot'])
def test_CardDBTokens(self):
cardDict = {
'Quick Shot': {
'type': 'Spell',
'hpwn': 14459,
'cdn': 'https://media-Hearth.cursecdn.com/14459.png',
'desc': 'Deal 3 damage. Draw a card.',
'hp': 1,
'class': 'Hunter',
'subType': 'Mech',
'set': 'Basic',
'rarity': 'Token',
'atk': 3,
'head': 'quick-shot',
'name': 'Quick Shot',
'cost': 2
}
}
constantDict = {
'sets' : { '01' : {'name' : 'Basic'} },
'specials' : { },
'alternative_names' : { }
}
with TempJson(constantDict) as constJson, \
TempJson(cardDict) as cardJson, \
TempJson({}) as emptyJson:
c = Constants(constJson)
db = CardDB(constants=c, cardJSON=emptyJson, duelsJSON=emptyJson, vanillaJSON=emptyJson, tokenJSON=cardJson, tempJSON=emptyJson)
self.assertEqual(db.cardNames(), ['quickshot'])
self.assertEqual(db.tokens, ['quickshot'])
self.assertTrue('quickshot' in db)
self.assertFalse('d!quickshot' in db)
self.assertFalse('c!quickshot' in db)
self.assertTrue('Quick Shot' in db['quickshot'])
def test_CardDBDuels(self):
cardDict = {
'Quick Shot': {
'type': 'Spell',
'hpwn': 14459,
'cdn': 'https://media-Hearth.cursecdn.com/14459.png',
'desc': 'Deal 3 damage. Draw a card.',
'hp': 1,
'class': 'Hunter',
'subType': 'Mech',
'set': 'Basic',
'rarity': 'Token',
'atk': 3,
'head': 'quick-shot',
'name': 'Quick Shot',
'cost': 2
}
}
constantDict = {
'sets' : { '01' : {'name' : 'Basic'} },
'specials' : { },
'alternative_names' : { }
}
with TempJson(constantDict) as constJson, \
TempJson(cardDict) as cardJson, \
TempJson({}) as emptyJson:
c = Constants(constJson)
db = CardDB(constants=c, cardJSON=emptyJson, duelsJSON=cardJson, vanillaJSON=emptyJson, tokenJSON=emptyJson, tempJSON=emptyJson)
self.assertEqual(db.cardNames(), ['quickshot'])
self.assertEqual(db.tokens, [])
self.assertTrue('quickshot' in db)
self.assertTrue('d!quickshot' in db)
self.assertFalse('c!quickshot' in db)
self.assertTrue('Quick Shot' in db['quickshot'])
self.assertTrue('Quick Shot' in db['d!quickshot'])
def test_CardDBVanilla(self):
cardDict = {
'Quick Shot': {
'type': 'Spell',
'hpwn': 14459,
'cdn': 'https://media-Hearth.cursecdn.com/14459.png',
'desc': 'Deal 3 damage. Draw a card.',
'hp': 1,
'class': 'Hunter',
'subType': 'Mech',
'set': 'Basic',
'rarity': 'Token',
'atk': 3,
'head': 'quick-shot',
'name': 'Quick Shot',
'cost': 2
}
}
constantDict = {
'sets' : { '01' : {'name' : 'Basic'} },
'specials' : { },
'alternative_names' : { }
}
with TempJson(constantDict) as constJson, \
TempJson(cardDict) as cardJson, \
TempJson({}) as emptyJson:
c = Constants(constJson)
db = CardDB(constants=c, cardJSON=emptyJson, duelsJSON=emptyJson, vanillaJSON=cardJson, tokenJSON=emptyJson, tempJSON=emptyJson)
self.assertEqual(db.cardNames(), ['quickshot'])
self.assertEqual(db.tokens, [])
self.assertTrue('quickshot' in db)
self.assertTrue('c!quickshot' in db)
self.assertFalse('d!quickshot' in db)
self.assertTrue('Quick Shot' in db['quickshot'])
self.assertTrue('Quick Shot' in db['c!quickshot'])
def test_RefreshCardDB(self):
cardDict = {
'Quick Shot': {
'type': 'Spell',
'hpwn': 14459,
'cdn': 'https://media-Hearth.cursecdn.com/14459.png',
'desc': 'Deal 3 damage. Draw a card.',
'hp': 1,
'class': 'Hunter',
'subType': "Mech",
'set': 'Basic',
'rarity': 'Common',
'atk': 3,
'head': 'quick-shot',
'name': 'Quick Shot',
'cost': 2
}
}
constantDict = {
'sets' : { '01' : {'name' : 'Basic'} },
'specials' : { },
'alternative_names' : { }
}
with TempJson(constantDict) as constJson, \
TempJson(cardDict) as cardJson, \
TempJson({}) as emptyJson:
c = Constants(constJson)
db = CardDB(constants=c, cardJSON=emptyJson, duelsJSON=emptyJson, vanillaJSON=emptyJson, tokenJSON=emptyJson, tempJSON='notexisting.json')
self.assertEqual(db.cardNames(), [])
self.assertFalse('quickshot' in db)
db.tempJSON = cardJson
db.refreshTemp()
self.assertTrue('quickshot' in db)
self.assertTrue('Quick Shot' in db['quickshot'])
class TestHelper(unittest.TestCase):
"""helper.py HSHelper"""
def test_QuoteCleaner(self):
self.assertEqual(HSHelper.removeQuotes("> b\na\n> b\nc"), "a c")
self.assertEqual(HSHelper.removeQuotes("> abc"), "")
def test_getCardsFromComment(self):
cardDict = {
'Quick Shot': {
'type': 'Spell',
'hpwn': 14459,
'cdn': 'https://media-Hearth.cursecdn.com/14459.png',
'desc': 'Deal 3 damage. Draw a card.',
'hp': 1,
'class': 'Hunter',
'subType': "Mech",
'set': 'Basic',
'rarity': 'Common',
'atk': 3,
'head': 'quick-shot',
'name': 'Quick Shot',
'cost': 2
}
}
# we need more cards (Card AA - Card UU)
for i in range(21):
name = 'Card ' + chr(97 + i)
cardDict[name] = cardDict['Quick Shot'].copy()
cardDict[name]['name'] = name
constantDict = {
'sets' : { '01' : {'name' : 'Basic'} },
'specials' : { },
'alternative_names' : { "quickshot" : "qs" }
}
with TempJson(constantDict) as constJson, \
TempJson(cardDict) as cardJson, \
TempJson({}) as emptyJson:
c = Constants(constJson)
db = CardDB(constants=c, cardJSON=cardJson, duelsJSON=emptyJson, vanillaJSON=emptyJson, tokenJSON=emptyJson, tempJSON=emptyJson)
helper = HSHelper(db, c)
# simple find
text = '[[Quick Shot]]'
cards, text = helper.parseText(text)
self.assertEqual(cards, ['quickshot'], 'simple card')
self.assertTrue('Quick Shot' in text)
# escaped simple find
text = '\\[\\[quickshot\\]\\]'
cards, text = helper.parseText(text)
self.assertEqual(cards, ['quickshot'], 'simple card')
self.assertTrue('Quick Shot' in text)
# two cards, cleanName
text = ' [[card a]] world [[quickshot 42]] '
cards, text = helper.parseText(text)
self.assertEqual(cards, ['carda', 'quickshot'], 'multi cards, clean')
self.assertTrue('Quick Shot' in text)
self.assertTrue('Card a' in text)
# spell check
text = '[[Quic Shot]]'
cards, text = helper.parseText(text)
self.assertEqual(cards, ['quickshot'], 'simple card')
self.assertTrue('Quick Shot' in text)
# alternative name
text = '[[QS]]'
cards, text = helper.parseText(text)
self.assertEqual(cards, ['quickshot'], 'alternative name')
self.assertTrue('Quick Shot' in text)
# test card limit always working
cardsNames = ['card' + chr(97 + i) for i in range(c.CARD_LIMIT + 1)]
cardsNames = ['no card'] + cardsNames
text = '[[' + ']][['.join(cardsNames) + ']]'
cards, text = helper.parseText(text)
self.assertEqual(cards, cardsNames[1:-1],
'CARD_LIMIT cards expected')
self.assertTrue('no card' not in text, 'unknown should be skipped')
for i in range(c.CARD_LIMIT):
self.assertTrue('Card ' + chr(97 + i) in text)
# test short text
text = '[[a]]'
cards, text = helper.parseText(text)
self.assertEqual(len(cards), 0, 'no cards')
self.assertEqual(len(text), 0, 'no cards')
# test no valid text
text = '[[123]] [abc]'
cards, text = helper.parseText(text)
self.assertEqual(len(cards), 0, 'no valid text')
self.assertEqual(len(text), 0, 'no valid text')
# card too long
text = '[[123456789012345678901234567890abc]]'
cards, text = helper.parseText(text)
self.assertEqual(len(cards), 0, 'card too long')
self.assertEqual(len(text), 0, 'card too long')
def test_loadInfoTempl_simple(self):
constantDict = {
'sets' : { },
'specials' : { 'dream' : ['no'] },
'alternative_names' : { 'quickshot' : 'qs' }
}
try:
if os.path.isfile('data/info_msg.templ'):
os.rename('data/info_msg.templ', 'data/_info_msg.templ')
with TempJson(constantDict) as constJson, \
TempJson({}) as emptyJson:
with open('data/info_msg.templ', 'w', newline="\n") as f:
f.write('{user}-{alts}-{tokens}-{special}')
c = Constants(constJson)
db = CardDB(constants=c, cardJSON=emptyJson, duelsJSON=emptyJson, vanillaJSON=emptyJson, tokenJSON=emptyJson, tempJSON=emptyJson)
helper = HSHelper(db, c)
info = helper.getInfoText('user')
self.assertEqual(info, 'user-qs--dream')
finally:
removeFile('data/info_msg.templ')
if os.path.isfile('data/_info_msg.templ'):
os.rename('data/_info_msg.templ', 'data/info_msg.templ')
def test_JsonFiles(self):
if os.path.isfile('data/tempinfo.json'):
with open('data/tempinfo.json', 'r') as infofile:
json.load(infofile)
if os.path.isfile("data/tokens.json"):
with open('data/tokens.json', 'r') as infofile:
json.load(infofile)
if os.path.isfile("data/cards.json"):
with open('data/cards.json', 'r') as infofile:
json.load(infofile)
if os.path.isfile("data/duels.json"):
with open('data/duels.json', 'r') as infofile:
json.load(infofile)
class TestSpelling(unittest.TestCase):
"""helper.py SpellChecker"""
def test_Spellchecker(self):
checker = SpellChecker(["abcdef"])
self.assertEqual(checker.correct("abcdef"), "abcdef")
self.assertEqual(checker.correct("abcde"), "abcdef")
self.assertEqual(checker.correct("bcdef"), "abcdef")
self.assertEqual(checker.correct("acdef"), "abcdef")
self.assertEqual(checker.correct("bacdef"), "abcdef")
self.assertEqual(checker.correct("abcdeg"), "abcdef")
self.assertEqual(checker.correct("aabcdef"), "abcdef")
# only distance 1 errors are fixed
self.assertEqual(checker.correct("abcd"), "abcd")
class TestBot(unittest.TestCase):
"""hearthscan-bot.py"""
def test_AnswerMail_UserOnSpam(self):
r = MagicMock()
msg = MagicMock()
msg.subreddit = None
msg.author.name = 'user'
msg.id = 'msgidus'
msg.distinguished = None
pmUserCache = {'user' : 1234}
helper = MagicMock()
# test
hsbot.answerPM(r, msg, pmUserCache, helper)
self.assertEqual(r.method_calls, [], 'no reddit calls')
self.assertEqual(helper.method_calls, [], 'no helper calls')
def test_AnswerMail_Success(self):
r = MagicMock()
msg = MagicMock()
msg.subreddit = None
msg.author.name = 'user'
msg.id = 'msgids'
msg.distinguished = None
msg.subject = 'sub'
msg.body = 'body'
pmUserCache = { }
helper = MagicMock()
helper.parseText = MagicMock(return_value=(['card'], 'text'))
# test
hsbot.answerPM(r, msg, pmUserCache, helper)
self.assertTrue('user' in pmUserCache, 'user added to cache')
self.assertEqual(r.method_calls, [], 'no reddit calls')
expected = [call.parseText('sub body')]
self.assertEqual(helper.method_calls, expected, 'parseText')
expected = [call.reply('text')]
self.assertEqual(msg.method_calls, expected, 'reply')
def test_Forward_PM(self):
r = MagicMock()
msg = MagicMock()
msg.subreddit = None
msg.author.name = 'user'
msg.id = 'msgidpm'
msg.distinguished = None
msg.subject = 'sub'
msg.body = 'body'
pmUserCache = { }
helper = MagicMock()
helper.parseText = MagicMock(return_value=([], ''))
redMsg = MagicMock()
r.redditor = MagicMock(return_value=redMsg)
# test
hsbot.answerPM(r, msg, pmUserCache, helper)
self.assertTrue('user' in pmUserCache, 'user added to cache')
expected = [call.redditor(credentials.admin_username)]
self.assertEqual(r.method_calls, expected, 'get redditor')
expected = [call.message('#msgidpm /u/user: "sub"', msg.body)]
self.assertEqual(redMsg.method_calls, expected, 'set message')
expected = [call.parseText('sub body')]
self.assertEqual(helper.method_calls, expected, 'parseText')
self.assertEqual(msg.method_calls, [], 'no reply')
def test_Forward_PM_Answer(self):
r = MagicMock()
msg = MagicMock()
msg.subreddit = None
msg.author.name = credentials.admin_username
msg.id = 'msgid2'
msg.distinguished = None
msg.subject = 're: #msgid1 /u/user: "sub"'
msg.body = 'body'
pmUserCache = { }
helper = MagicMock()
helper.parseText = MagicMock(return_value=([], 'text'))
oldMsg = MagicMock()
r.inbox.message = MagicMock(return_value=oldMsg)
# test
hsbot.answerPM(r, msg, pmUserCache, helper)
self.assertTrue(msg.author.name not in pmUserCache, "don't admin")
expected = [call.inbox.message('msgid1')]
self.assertEqual(r.method_calls, expected, 'reddit call')
expected = [call.message('msgid1')]
self.assertEqual(r.inbox.method_calls, expected, 'get old msg')
expected = [call.reply('body')]
self.assertEqual(oldMsg.method_calls, expected, 'reply old')
expected = [call.reply('answer forwarded')]
self.assertEqual(msg.method_calls, expected, 'reply new')
self.assertEqual(helper.method_calls, [], 'no helper calls')
def test_CleamPMUserCache(self):
future = int(time.time()) + 60
cache = {"aaa": 123, "bbb": future}
hsbot.cleanPMUserCache(cache)
self.assertIsNone(cache.get("aaa"))
self.assertEqual(cache["bbb"], future)
if __name__ == '__main__':
removeFile("test.log")
logging.basicConfig(filename="test.log",
format='%(asctime)s %(levelname)s %(name)s %(message)s',
level=logging.DEBUG)
print("run 'test.py online' to test online scraping functionality")
# lazy argv fix
unittest.main(warnings='ignore', argv=[sys.argv[0]])