/
anki_testing.py
83 lines (56 loc) · 1.95 KB
/
anki_testing.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
# coding: utf-8
import shutil
import tempfile
from contextlib import contextmanager
import os
import sys
from warnings import warn
sys.path.insert(0, 'anki_root')
import aqt
from aqt import _run
from aqt import AnkiApp
from aqt.profiles import ProfileManager
@contextmanager
def temporary_user(dir_name, name="__Temporary Test User__", lang="en_US"):
# prevent popping up language selection dialog
original = ProfileManager.setDefaultLang
def set_default_lang(profileManager):
profileManager.setLang(lang)
ProfileManager.setDefaultLang = set_default_lang
pm = ProfileManager(base=dir_name)
pm.setupMeta()
# create profile no matter what (since we are starting in a unique temp directory)
pm.create(name)
# this needs to be called explicitly
pm.setDefaultLang()
pm.name = name
yield name
# cleanup
pm.remove(name)
ProfileManager.setDefaultLang = original
@contextmanager
def temporary_dir(name):
# create a true unique temporary directory at every startup
tempdir = tempfile.TemporaryDirectory(suffix='anki')
yield tempdir.name
@contextmanager
def anki_running():
# don't use the second instance mechanism, start a new instance every time
def mock_secondInstance(ankiApp):
return False
AnkiApp.secondInstance = mock_secondInstance
# we need a new user for the test
with temporary_dir("anki_temp_base") as dir_name:
with temporary_user(dir_name) as user_name:
argv=["anki", "-p", user_name, "-b", dir_name]
print(f'running anki with argv={argv}')
app = _run(argv=argv, exec=False)
yield app
# clean up what was spoiled
aqt.mw.cleanupAndExit()
# remove hooks added during app initialization
from anki import hooks
hooks._hooks = {}
# test_nextIvl will fail on some systems if the locales are not restored
import locale
locale.setlocale(locale.LC_ALL, locale.getdefaultlocale())