Hey all,
I’m trying to set up some tests on my addon.
This looks like, in a test file,
import my_addon.thing_to_test
test_thing_to_test():
assert thing_to_test() == 'expected'
Unfortunately this conflicts with Anki add-on initialization. As per docs, in my_addon/__init__.py
, I am running all my hook initialization and stuff.
#my_addon/__init__.py
from .thing_to_test import card_will_show
import aqt.gui_hooks
aqt.gui_hooks.card_will_show.append(card_will_show)
aqt.mw.addonManager.setWebExports(__name__, 'web/.*')
This means my addon can’t be imported under pytest (or in any context that isn’t a running Anki gui), because it will always run all this initialization code, which fails if e.g. anki.mw doesn’t exist.
The normal way we’d deal with this in python is to put all the setup stuff into a function and only execute it under certain conditions. E.g. a common pattern would be
def main():
import aqt.gui_hooks
from .thing_to_test import card_will_show
aqt.gui_hooks.card_will_show.append(card_will_show)
aqt.mw.addonManager.setWebExports(__name__, 'web/.*')
if __name__== '__main__':
main()
Is there any way I can do something like the above in my Anki addon? e.g.
-
if __name__ == 'ANKII_SETUP_MAGIC_STR': ...
, -
def magic_anki_init_function(): ...
, - etc .
Cheers!