Best Python code snippet using localstack_python
test_adrc_unit.py
Source:test_adrc_unit.py  
1"""unit tests for loanpy.adrc.py 2.0 BETA with pytest 7.1.1"""2from collections import OrderedDict3from os import remove4from pathlib import Path5from unittest.mock import patch, call6from pandas import DataFrame7from loanpy.adrc import Adrc, read_scdictlist, move_sc8from loanpy.qfysc import Etym9class AdrcMonkey:10    pass11def test_read_scdictlist():12    """test if list of sound correspondence dictionaries is read correctly"""13    # no set up needed for this assertion:14    assert read_scdictlist(None) == [None, None, None, None, None]15    # set up: creat a mock list of dicts and write it to file16    dict0 = {"dict0": "szia"}17    dict1 = {"dict1": "csÅ"}18    out = [dict0, dict1, dict0, dict1]19    path = Path(__file__).parent / "test_read_scdictlist.txt"20    with open(path, "w", encoding="utf-8") as f:21        f.write(str(out))22    # set up: mock literal_eval23    with patch("loanpy.adrc.literal_eval") as literal_eval_mock:24        literal_eval_mock.return_value = out25        # assert mock dict list is read in correctly26        assert read_scdictlist(path) == out27        # assert call28        literal_eval_mock.assert_called_with(str(out))29    # tear down30    remove(path)31    del dict0, dict1, out, path32def test_move_sc():33    """test if sound correspondences are moved correctly"""34    # no setup, teardown, or patch needed here35    assert move_sc(sclistlist=[["x", "x"]], whichsound=0,36                   out=[[]]) == ([["x"]], [["x"]])37    assert move_sc(sclistlist=[["x", "x"], ["y", "y"], ["z"]], whichsound=0,38                   out=[["a"], ["b"], ["c"]]) == ([["x"], ["y", "y"], ["z"]],39                                                  [["a", "x"], ["b"], ["c"]])40    assert move_sc(sclistlist=[["x", "x"], ["y", "y"], ["z"]], whichsound=1,41                   out=[["a"], ["b"], ["c"]]) == ([["x", "x"], ["y"], ["z"]],42                                                  [["a"], ["b", "y"], ["c"]])43    assert move_sc(sclistlist=[["", "x", "$"], ["", "y", "$"], ["", "$"]],44                   whichsound=1, out=[["a"], ["b"], ["c"]]) == (45        [["", "x", "$"], ["y", "$"], ["", "$"]], [["a"], ["b", "y"], ["c"]])46    assert move_sc(sclistlist=[["", "$"], ["", "$"], ["Z", "2", "$"]],47                   whichsound=2, out=[["o"], ["r"], ["f"]]) == (48        [["", "$"], ["", "$"], ["2", "$"]], [["o"], ["r"], ["f", "2"]])49def test_init():50    """test if the Adrc-class is initiated properly"""51    # set up: mock super() method and read_scdictlist52    # define side_effect of read_scdictlist in vars53    # initiate the real class54    with patch("loanpy.adrc.Etym.__init__") as super_method_mock:55        with patch("loanpy.adrc.read_scdictlist") as read_scdictlist_mock:56            read_scdictlist_mock.return_value = [None] * 557            monkey_adrc = Adrc()58            # assert initiation went correctly59            assert monkey_adrc.scdict is None60            assert monkey_adrc.sedict is None61            assert monkey_adrc.edict is None62            assert monkey_adrc.scdict_phonotactics is None63            assert monkey_adrc.workflow == OrderedDict()64            # double check with __dict__65            assert len(monkey_adrc.__dict__) == 666            assert monkey_adrc.__dict__ == {67                'edict': None,68                'scdict': None,69                'probdict': None,70                'scdict_phonotactics': None,71                'sedict': None,72                'workflow': OrderedDict()}73    # assert calls74    super_method_mock.assert_called_with(75        forms_csv=None,76        source_language=None,77        target_language=None,78        adapting=True,79        scdictbase=None)80    assert read_scdictlist_mock.call_args_list == [call(None)]81    # set up: mock super() method and read_scdictlist82    # define side_effect of read_scdictlist in vars83    # initiate the real class84    with patch("loanpy.adrc.Etym.__init__") as super_method_mock:85        d0, d1, d2, d3, d4 = {"d0": None}, {"d1": None}, {86            "d2": None}, {"d3": None}, {"d4": None}87        with patch("loanpy.adrc.read_scdictlist") as read_scdictlist_mock:88            read_scdictlist_mock.return_value = [d0, d1, d2, d3, d4]89            monkey_adrc = Adrc(90                scdictlist="soundchanges.txt",91                forms_csv="forms.csv",92                adapting=False93                )94            # assert initiation went correctly95            assert monkey_adrc.scdict == d096            assert monkey_adrc.sedict == d197            assert monkey_adrc.edict == d298            assert monkey_adrc.probdict == d399            assert monkey_adrc.scdict_phonotactics == d4100            assert monkey_adrc.workflow == OrderedDict()101            # double check with __dict__102            assert len(monkey_adrc.__dict__) == 6103            assert monkey_adrc.__dict__ == {104                'edict': {'d2': None},105                'scdict': {'d0': None},106                'scdict_phonotactics': {'d4': None},107                'probdict': {'d3': None},108                'sedict': {'d1': None},109                'workflow': OrderedDict()}110    # assert calls111    super_method_mock.assert_called_with(112        forms_csv='forms.csv', source_language=None, target_language=None,113        adapting=False,114        scdictbase=None)115    assert read_scdictlist_mock.call_args_list == [call("soundchanges.txt")]116    # tear down117    del d0, d1, d2, d3, monkey_adrc118def test_get_diff():119    """test if the difference is calculated correctly120    between the first two sound of a sound correspondence list"""121    # test without exception122    # set up: mock class, 2 attributes, 1 var for input-param123    monkey_adrc = AdrcMonkey()124    monkey_adrc.sedict = {"k<k": 2, "k<c": 1, "i<e": 2, "i<o": 1}125    monkey_adrc.connector = "<"126    sclistlist = [["k", "c", "$"], ["e", "o", "$"],127                  ["k", "c", "$"], ["e", "o", "$"]]128    # assert129    assert Adrc.get_diff(130        self=monkey_adrc,131        sclistlist=sclistlist,132        ipa=["k", "i", "k", "i"]) == [1, 1, 1, 1]133    # there were no mock calls, so no calls to assert134    # test first exception135    # set up: mock class, 2 attributes, 1 var for input-param136    monkey_adrc = AdrcMonkey()137    monkey_adrc.sedict = {"k<k": 2, "k<c": 1, "i<e": 2, "i<o": 1}138    monkey_adrc.connector = "<"139    sclistlist = [["k", "c", "x"], ["x", "$"]]140    # assert141    assert Adrc.get_diff(142        self=monkey_adrc,143        sclistlist=sclistlist,144        ipa=["k", "i"]) == [1, float("inf")]145    # no calls made so no calls to assert146    # test second exception147    # set up: mock class, 2 attributes, 1 var for input-param148    monkey_adrc = AdrcMonkey()149    monkey_adrc.sedict = {"k<k": 0, "k<c": 0, "i<e": 7, "i<o": 1}150    monkey_adrc.connector = "<"151    sclistlist = [["k", "c", "x"], ["e", "o", "x"]]152    # assert 1153    assert Adrc.get_diff(154        self=monkey_adrc,155        sclistlist=sclistlist,156        ipa=["k", "i"]) == [9999999, 6]157    # teardown/setup: overwrite attribute nsedict158    monkey_adrc.sedict = {"k<k": 0, "k<c": 0, "i<e": 7, "i<o": 7}159    # assert 2160    assert Adrc.get_diff(161        self=monkey_adrc,162        sclistlist=sclistlist,163        ipa=["k", "i"]) == [9999999, 0]164    # teardown/setup: overwrite attribute nsedict165    monkey_adrc.sedict = {"k<k": 0, "k<c": 0, "i<e": 0, "i<o": 0}166    # assert 3167    assert Adrc.get_diff(168        self=monkey_adrc,169        sclistlist=sclistlist,170        ipa=["k", "i"]) == [9999999, 9999999]171    # no calls made so no calls to assert172    # tear down173    del monkey_adrc, sclistlist174def test_read_sc():175    """test if sound correspondences are read correctly"""176    # set up mock class177    class AdrcMonkeyread_sc:178        def __init__(self, get_diff=""):179            self.get_diff_returns = iter(get_diff)180            self.get_diff_called_with = []181        def get_diff(self, sclistlist, ipa):182            self.get_diff_called_with.append((sclistlist, ipa))183            return next(self.get_diff_returns)184    # test if first break works (max)185    # set up mock class, plug in mock scdict, mock tokenise, mock math.prod186    monkey_adrc = AdrcMonkeyread_sc()187    monkey_adrc.scdict = {"k": ["k", "h"], "i": ["e", "o"]}188    with patch("loanpy.adrc.prod") as prod_mock:189        prod_mock.return_value = 16190        # assert191        assert Adrc.read_sc(self=monkey_adrc, ipa=["k", "i", "k", "i"],192                            howmany=1000) == [193            ["k", "h"], ["e", "o"], ["k", "h"], ["e", "o"]]194    # assert 3 calls: get_diff, prod_mock, tokenise195    assert monkey_adrc.get_diff_called_with == []  # not called!196    prod_mock.assert_called_with([2, 2, 2, 2])197    # test if second break works (min)198    # set up mock class, plug in mock scdict, mock math.prod199    monkey_adrc = AdrcMonkeyread_sc()200    monkey_adrc.scdict = {"k": ["k", "h"], "i": ["e", "o"]}201    with patch("loanpy.adrc.prod", side_effect=[16, 1]) as prod_mock:202        # assert read_sc works with tokenised list as input203        assert Adrc.read_sc(204            self=monkey_adrc,205            ipa=["k", "i", "k", "i"],206            howmany=1) == [["k"], ["e"], ["k"], ["e"]]207    # assert 2 calls: get_diff, prod_mock208    assert monkey_adrc.get_diff_called_with == []  # not called!209    assert prod_mock.call_args_list == [210        call([2, 2, 2, 2]), call([1, 1, 1, 1])]211    # test while loop with 1 minimum212    # set up mock class, plug in mock scdict, mock move_sc, mock math.prod213    monkey_adrc = AdrcMonkeyread_sc(get_diff=[[4, 5]])214    monkey_adrc.scdict = {"k": ["k", "h"], "i": ["e", "o"]}215    with patch("loanpy.adrc.move_sc") as move_sc_mock:216        move_sc_mock.return_value = ([["$"], ["o", "$"]], [["k", "h"], ["e"]])217        with patch("loanpy.adrc.prod", side_effect=[4, 1, 2]) as prod_mock:218            # assert sound correspondences are read in correctly219            assert Adrc.read_sc(self=monkey_adrc, ipa=["k", "i"],220                                howmany=2) == [221                ["k", "h"], ["e"]]222    # assert 3 calls: prod_mock, get_diff, move_sc223    assert prod_mock.call_args_list == [224        call([2, 2]), call([1, 1]), call([2, 1])]225    assert monkey_adrc.get_diff_called_with == [226        ([["k", "h", "$"], ["e", "o", "$"]], ["k", "i"])]227    move_sc_mock.assert_called_with(228        [["k", "h", "$"], ["e", "o", "$"]], 0, [["k"], ["e"]])229    # test while loop with 2 minima (ð²)230    # set up mock class, plug in mock scdict,231    # def var for side_effect of move_sc, mock move_sc, mock math.prod232    monkey_adrc = AdrcMonkeyread_sc(get_diff=[[2, 2, 5], [2, 2, 5], [3, 2, 5]])233    monkey_adrc.scdict = {"k": ["k", "h", "s"], "i": ["e", "o"],234                          "p": ["b", "v"]}235    se_move_sc = [236        ([["s", "$"], ["o", "$"], ["v", "$"]], [["k", "h"], ["e"], ["b"]]),237        ([["s", "$"], ["$"], ["v", "$"]], [["k", "h"], ["e", "o"], ["b"]])238    ]239    with patch("loanpy.adrc.move_sc", side_effect=se_move_sc) as move_sc_mock:240        with patch("loanpy.adrc.prod", side_effect=[241                12, 1, 1, 2, 4]) as prod_mock:242            # prod "3" gets only called once, bc difflist1!=difflist2, so 2nd243            # while loop doesnt call prod244            # assert read_sc works245            assert Adrc.read_sc(self=monkey_adrc, ipa=["k", "i", "p"],246                                howmany=3) == [["k", "h"], ["e", "o"], ["b"]]247    # assert calls: prod_mock, get_diff, move_sc248    assert prod_mock.call_args_list == [call([3, 2, 2]), call(249        [1, 1, 1]), call([1, 1, 1]), call([2, 1, 1]), call([2, 2, 1])]250    assert monkey_adrc.get_diff_called_with == [251        ([["k", "h", "s", "$"], ["e", "o", "$"], ["b", "v", "$"]],252         ["k", "i", "p"]),253        ([["s", "$"], ["o", "$"], ["v", "$"]], ["k", "i", "p"]),254        ([["s", "$"], ["$"], ["v", "$"]], ["k", "i", "p"])]255    assert move_sc_mock.call_args_list == [256        call([["k", "h", "s", "$"], ["e", "o", "$"], ["b", "v", "$"]],257             0, [["k"], ["e"], ["b"]]),258        call([["s", "$"], ["o", "$"], ["v", "$"]],259             1, [["k", "h"], ["e"], ["b"]])]260    # tear down261    del AdrcMonkeyread_sc, monkey_adrc, se_move_sc262def test_reconstruct():263    """test if reconstructions based on sound correspondences work"""264    # test first break: some sounds are not in scdict265    # set up mock class, plug in mock scdict, mock clusterise266    monkey_adrc = AdrcMonkey()267    monkey_adrc.scdict = {"#-": ["-"], "#k": ["k", "h"], "k": ["h"],268                          "-#": ["-"]}269    # assert reconstruct works270    assert Adrc.reconstruct(271        self=monkey_adrc,272        ipastr="k i k i") == "i, i# not old"273    # test 2nd break: phonotactics_filter and vowelharmony_filter are False274    # set up mock class, will be used multiple times throughout this test275    class AdrcMonkeyReconstruct:276        def __init__(277            self,278            read_sc_returns,279            harmony_returns=""):280            self.read_sc_called_with = []281            self.read_sc_returns = read_sc_returns282            self.harmony_returns = iter(harmony_returns)283            self.harmony_called_with = []284            self.get_nse_returns = iter([285            (20, "bli"), (4, "bla"), (99, "blu"), (17, "blo")])286            self.get_nse_called_with = []287            self.inventories = {288            "Segments": {},289            "CV_Segments": {},290            "ProsodicStructure": {}291            }292        def read_sc(self, ipalist, howmany):293            self.read_sc_called_with.append((ipalist, howmany))294            return self.read_sc_returns295        def has_harmony(self, *args):296            self.harmony_called_with.append([*args])297            return next(self.harmony_returns)298        def get_nse(self, *args):299            self.get_nse_called_with.append([*args])300            return next(self.get_nse_returns)301    # set up: create instance of mock class302    monkey_adrc = AdrcMonkeyReconstruct(303        read_sc_returns=[["-"], ["k"], ["i"], ["h"], ["e"], ["-"]])304    # set up: plug in sound correspondence dictionary into mock class305    monkey_adrc.scdict = {306        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "e"],307        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]308    }309    # set up: mock tokenise, mock list2regex310    with patch("loanpy.adrc.list2regex", side_effect=[311            "(k)", "(i)", "(h)", "(e)"]) as list2regex_mock:312        # assert reconstruct works313        assert Adrc.reconstruct(314            self=monkey_adrc,315            ipastr="k i k i",316            ) == "^(k) (i) (h) (e)$"317    # assert 3 calls: tokenise, read_sc, list2regex318    assert monkey_adrc.read_sc_called_with == [319        (['#-', '#k', 'i', 'k', 'i#', '-#'], 1)]320    assert list2regex_mock.call_args_list == [321        call(["k"]), call(["i"]),322        call(["h"]), call(["e"])]323    # test same break again but param <howmany> is greater than 1 now324    # set up325    monkey_adrc = AdrcMonkeyReconstruct(326        read_sc_returns=[["-"], ["k", "h"], ["i"], ["h"], ["e"], ["-"]])327    monkey_adrc.scdict = {328        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "e"],329        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]330    }331    # mock clusterise, list2regex332    with patch("loanpy.adrc.list2regex", side_effect=[333            "(k|h)", "(i)", "(h)", "(e)"]) as list2regex_mock:334        # assert reconstruct works335        assert Adrc.reconstruct(336            self=monkey_adrc,337            ipastr="k i k i",338            howmany=2) == "^(k|h) (i) (h) (e)$"339    # assert 3 calls: clusterise, read_sc, list2regex340    assert monkey_adrc.read_sc_called_with == [341        (['#-', '#k', 'i', 'k', 'i#', '-#'], 2)]342    assert list2regex_mock.call_args_list == [343        call(["k", "h"]), call(["i"]),344        call(["h"]), call(["e"])]345    # test with phonotactics_filter=True346    # teardown/setup: overwrite mock class, plug in mock scdict,347    # plug in mock phonotactic_inventory348    monkey_adrc = AdrcMonkeyReconstruct(349        read_sc_returns=[["-"], ["k", "h"], ["i", "e.i"], ["h"], ["e"], ["-"]])350    monkey_adrc.scdict = {351        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "ei"],352        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]353    }354    monkey_adrc.inventories["ProsodicStructure"] = ["CVVCV"]355    # set up: mock tokenise356    with patch("loanpy.adrc.prosodic_string",357    side_effect=["CVCV", "CVVCV", "CVCV", "CVVCV"]) as prosodic_string_mock:358        # assert reconstruct works359        assert Adrc.reconstruct(360            self=monkey_adrc,361            ipastr="k i k i",362            howmany=3,363            phonotactics_filter=True,364            ) == "^k e.i h e$|^h e.i h e$"365    # assert 3 calls: tokenise, read_sc, word2phonotactics366    assert monkey_adrc.read_sc_called_with == [367        (['#-', '#k', 'i', 'k', 'i#', '-#'], 3)]368    prosodic_string_mock.assert_has_calls([call(list(i)) for i in369        ["kihe", "keihe", "hihe", "heihe"]])370    # test phonotactics_filter=True, result empty371    # teardown/setup: overwrite mock class, plug in mock scdict372    # and phonotactic_inventory373    monkey_adrc = AdrcMonkeyReconstruct(374        read_sc_returns=[["-"], ["k", "h"], ["i", "ei"], ["h"], ["e"], ["-"]])375    monkey_adrc.scdict = {376        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "ei"],377        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]378    }379    monkey_adrc.phonotactic_inventory = ["CCCVVVVCV"]380    # set up: mock clusterise381    # assert reconstruct works382    assert Adrc.reconstruct(383        self=monkey_adrc,384        ipastr="k i k i",385        howmany=3,386        phonotactics_filter=True) == "wrong phonotactics"387    # assert 3 calls: clusterise, read_sc, word2phonotactics388    assert monkey_adrc.read_sc_called_with == [389        (['#-', '#k', 'i', 'k', 'i#', '-#'], 3)]390    prosodic_string_mock.assert_has_calls([call(list(i)) for i in391        ["kihe", "keihe", "hihe", "heihe"]])392    # test phonotactics_filter=True, result empty,393    # teardown/setup: overwrite mock class, plug in mock scdict,394    # phonotactic_inventory395    monkey_adrc = AdrcMonkeyReconstruct(396        read_sc_returns=[["-"], ["k", "h"], ["i", "ei"], ["h"], ["e"], ["-"]])397    monkey_adrc.scdict = {398        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "ei"],399        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]400    }401    monkey_adrc.phonotactic_inventory = ["CCCVVVVCV"]402    # set up: mock tokenise403    # assert reconstruct works (returns an error message as string)404    assert Adrc.reconstruct(405        self=monkey_adrc,406        ipastr="k i k i",407        howmany=3,408        phonotactics_filter=True,409        ) == "wrong phonotactics"410    # assert 3 calls: tokenise, read_sc, word2phonotactics411    assert monkey_adrc.read_sc_called_with == [412        (['#-', '#k', 'i', 'k', 'i#', '-#'], 3)]413    prosodic_string_mock.assert_has_calls([call(list(i)) for i in414        ["kihe", "keihe", "hihe", "heihe"]])415    # test vowelharmony_filter=True416    # teardown/setup: overwrite mock class, plug in scdict417    monkey_adrc = AdrcMonkeyReconstruct(read_sc_returns=[418        ["-"], ["k", "h"], ["i", "o"], ["h"], ["e"], ["-"]], harmony_returns=[419        True, False, True, False])420    monkey_adrc.scdict = {421        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "o"],422        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]423    }424    # setup: mock tokenise425    with patch("loanpy.adrc.has_harmony",426    side_effect=[True, False, True, False]) as has_harmony_mock:427        # assert reconstruct works with vowelharmony_filter=True428        assert Adrc.reconstruct(429            self=monkey_adrc,430            ipastr="k i k i",431            howmany=3,432            vowelharmony_filter=True,433            ) == "^k i h e$|^h i h e$"434    # assert 3 calls: tokenise, read_sc, has_harmony435    assert monkey_adrc.read_sc_called_with == [436        (['#-', '#k', 'i', 'k', 'i#', '-#'], 3)]437    has_harmony_mock.assert_has_calls([call(i.split(" ")) for i in [438        "k i h e", "k o h e", "h i h e", "h o h e"]])439    # test vowelharmony_filter=True, result is empty440    # teardowns/setup: overwrite mock class, plug in scdict441    monkey_adrc = AdrcMonkeyReconstruct(442        read_sc_returns=[["-"], ["k", "h"], ["i", "o"], ["h"], ["e"], ["-"]],443    )444    monkey_adrc.scdict = {445        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "o"],446        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]447    }448    # setup: mock tokenise449    with patch("loanpy.adrc.has_harmony") as has_harmony_mock:450        has_harmony_mock.return_value = False451        # assert reconstruct works (returns error message as string)452        assert Adrc.reconstruct(453            self=monkey_adrc,454            ipastr="k i k i",455            howmany=3,456            vowelharmony_filter=True,457            ) == "wrong vowel harmony"458    # assert 3 calls: tokenise, read_sc, has_harmony459    assert monkey_adrc.read_sc_called_with == [460        (['#-', '#k', 'i', 'k', 'i#', '-#'], 3)]461    has_harmony_mock.assert_has_calls([call(i.split(" ")) for i in [462        "k i h e", "k o h e", "h i h e", "h o h e"]])463    # test sort_by_nse=9999999464    # teardown/setup: overwrite mock class, plug in scdict465    monkey_adrc = AdrcMonkeyReconstruct(466        read_sc_returns=[["-"], ["k", "h"], ["i", "o"], ["h"], ["e"], ["-"]],467    )  # unsorted: kihe, kohe, hihe, hohe (like odometer, help(itertools.prod))468    monkey_adrc.scdict = {469        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "o"],470        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]471    }472    # set up: mock tokenise473    with patch("loanpy.adrc.nlargest") as nlargest_mock:474        nlargest_mock.return_value = [(99, "h i h e"), (20, "k i h e"), (17, "h o h e"), (4, "k o h e")]475        # assert reconstruct works and sorts the result by nse476        assert Adrc.reconstruct(477            self=monkey_adrc,478            ipastr="k i k i",479            howmany=9999999,480            sort_by_nse=9999999,481            ) == "^h i h e$|^k i h e$|^h o h e$|^k o h e$"482    # assert 3 calls: tokenise, read_sc, and get_nse483    nlargest_mock.assert_called_with(9999999, [484        (20, "k i h e"), (4, "k o h e"), (99, "h i h e"), (17, "h o h e")])485    assert monkey_adrc.read_sc_called_with == [486        (['#-', '#k', 'i', 'k', 'i#', '-#'], 9999999)]487    assert monkey_adrc.get_nse_called_with == [["k i k i", "k i h e"], [488        "k i k i", "k o h e"], ["k i k i", "h i h e"], ["k i k i", "h o h e"]]489    # test sort_by_nse=1490    # teardown/setup: overwrite mock class, plug in scdict491    monkey_adrc = AdrcMonkeyReconstruct(492        read_sc_returns=[["-"], ["k", "h"], ["i", "o"], ["h"], ["e"], ["-"]],493    )  # unsorted: kihe, kohe, hihe, hohe (like odometer, help(itertools.prod))494    monkey_adrc.scdict = {495        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "o"],496        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]497    }498    # set up: mock tokenise, nlargest499    with patch("loanpy.adrc.nlargest") as nlargest_mock:500        nlargest_mock.return_value = [(99, "h i h e")]501        # assert reconstruct works and picks 1 word with highest nse502        assert Adrc.reconstruct(503            self=monkey_adrc,504            ipastr="k i k i",505            howmany=9999999,506            sort_by_nse=1,507            ) == "^h i h e$|^k i h e$|^k o h e$|^h o h e$"508    # assert 4 calls: tokenise, read_sc, and get_nse, nlargest509    nlargest_mock.assert_called_with(1,510        [(20, "k i h e"), (4, "k o h e"), (99, "h i h e"), (17, "h o h e")])511    assert monkey_adrc.read_sc_called_with == [512        (['#-', '#k', 'i', 'k', 'i#', '-#'], 9999999)]513    assert monkey_adrc.get_nse_called_with == [["k i k i", "k i h e"], [514        "k i k i", "k o h e"], ["k i k i", "h i h e"], ["k i k i", "h o h e"]]515    # test sort_by_nse=2516    # teardown/setup: overwrite mock class, plug in scdict517    monkey_adrc = AdrcMonkeyReconstruct(518        read_sc_returns=[["-"], ["k", "h"], ["i", "o"], ["h"], ["e"], ["-"]],519    )  # unsorted: kihe, kohe, hihe, hohe (like odometer, help(itertools.prod))520    monkey_adrc.scdict = {521        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "o"],522        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]523    }524    # set up: mock tokenise, nlargest525    with patch("loanpy.adrc.nlargest") as nlargest_mock:526        nlargest_mock.return_value = [(99, "h i h e"), (20, "k i h e")]527        # assert reconstruct works and picks 1 word with highest nse528        assert Adrc.reconstruct(529            self=monkey_adrc,530            ipastr="k i k i",531            howmany=9999999,532            sort_by_nse=2,533            ) == "^h i h e$|^k i h e$|^k o h e$|^h o h e$"534    # assert 4 calls: tokenise, read_sc, and get_nse, nlargest535    nlargest_mock.assert_called_with(2,536        [(20, "k i h e"), (4, "k o h e"), (99, "h i h e"), (17, "h o h e")])537    assert monkey_adrc.read_sc_called_with == [538        (['#-', '#k', 'i', 'k', 'i#', '-#'], 9999999)]539    assert monkey_adrc.get_nse_called_with == [["k i k i", "k i h e"], [540        "k i k i", "k o h e"], ["k i k i", "h i h e"], ["k i k i", "h o h e"]]541    # test sort_by_nse=3542    # teardown/setup: overwrite mock class, plug in scdict543    monkey_adrc = AdrcMonkeyReconstruct(544        read_sc_returns=[["-"], ["k", "h"], ["i", "o"], ["h"], ["e"], ["-"]],545    )  # unsorted: kihe, kohe, hihe, hohe (like odometer, help(itertools.prod))546    monkey_adrc.scdict = {547        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "o"],548        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]549    }550    # set up: mock tokenise, nlargest551    with patch("loanpy.adrc.nlargest") as nlargest_mock:552        nlargest_mock.return_value = [(99, "h i h e"), (20, "k i h e"), (17, "h o h e")]553        # assert reconstruct works and picks 1 word with highest nse554        assert Adrc.reconstruct(555            self=monkey_adrc,556            ipastr="k i k i",557            howmany=9999999,558            sort_by_nse=3,559            ) == "^h i h e$|^k i h e$|^h o h e$|^k o h e$"560    # assert 4 calls: tokenise, read_sc, and get_nse, nlargest561    nlargest_mock.assert_called_with(3,562        [(20, "k i h e"), (4, "k o h e"), (99, "h i h e"), (17, "h o h e")])563    assert monkey_adrc.read_sc_called_with == [564        (['#-', '#k', 'i', 'k', 'i#', '-#'], 9999999)]565    assert monkey_adrc.get_nse_called_with == [["k i k i", "k i h e"], [566        "k i k i", "k o h e"], ["k i k i", "h i h e"], ["k i k i", "h o h e"]]567    # test sort_by_nse=0568    # teardown/setup: overwrite mock class, plug in scdict569    monkey_adrc = AdrcMonkeyReconstruct(570        read_sc_returns=[["-"], ["k", "h"], ["i", "o"], ["h"], ["e"], ["-"]],571    )  # unsorted: kihe, kohe, hihe, hohe (like odometer, help(itertools.prod))572    monkey_adrc.scdict = {573        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "o"],574        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]575    }576    # set up: mock tokenise, nlargest577    with patch("loanpy.adrc.nlargest") as nlargest_mock:578        # assert reconstruct works and picks 0 words with highest nse579        assert Adrc.reconstruct(580            self=monkey_adrc,581            ipastr="k i k i",582            howmany=9999999,583            sort_by_nse=0,584            ) == "^(k|h) (i|o) (h) (e)$"585    # assert 4 calls: tokenise, read_sc, and get_nse, nlargest586    nlargest_mock.assert_not_called()587    assert monkey_adrc.read_sc_called_with == [588        (['#-', '#k', 'i', 'k', 'i#', '-#'], 9999999)]589    assert monkey_adrc.get_nse_called_with == []590    # test sort_by_nse=0591    # teardown/setup: overwrite mock class, plug in scdict592    monkey_adrc = AdrcMonkeyReconstruct(593        read_sc_returns=[["-"], ["k", "h"], ["i", "o"], ["h"], ["e"], ["-"]],594    )  # unsorted: kihe, kohe, hihe, hohe (like odometer, help(itertools.prod))595    monkey_adrc.scdict = {596        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "o"],597        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]598    }599    # set up: mock tokenise, nlargest600    with patch("loanpy.adrc.nlargest") as nlargest_mock:601        # assert reconstruct works and picks 0 words with highest nse602        assert Adrc.reconstruct(603            self=monkey_adrc,604            ipastr="k i k i",605            howmany=9999999,606            sort_by_nse=0,607            ) == "^(k|h) (i|o) (h) (e)$"608    # assert 4 calls: tokenise, read_sc, and get_nse, nlargest609    nlargest_mock.assert_not_called()610    assert monkey_adrc.read_sc_called_with == [611        (['#-', '#k', 'i', 'k', 'i#', '-#'], 9999999)]612    assert monkey_adrc.get_nse_called_with == []613    # test sort_by_nse=0, but combinatorics applied b/c614    # phonotactics_filter=True615    # teardown/setup: overwrite mock class, plug in scdict616    monkey_adrc = AdrcMonkeyReconstruct(617        read_sc_returns=[["-"], ["k", "h"], ["i", "o"], ["h"], ["e"], ["-"]])  # unsorted: kihe, kohe, hihe, hohe (like odometer, help(itertools.prod))618    monkey_adrc.scdict = {619        "#-": ["-"], "#k": ["k", "h"], "i": ["i", "o"],620        "k": ["h"], "i#": ["e", "o"], "-#": ["-"]621    }622    monkey_adrc.inventories["ProsodicStructure"] = ["CVCV"]  # let's all thru filter!623    # set up: mock tokenise, nlargest624    with patch("loanpy.adrc.prosodic_string") as prosodic_string_mock:625        prosodic_string_mock.return_value="CVCV"626        with patch("loanpy.adrc.nlargest") as nlargest_mock:627            # assert reconstruct works and picks 0 words with highest nse628            assert Adrc.reconstruct(629                self=monkey_adrc,630                ipastr="k i k i",631                howmany=9999999,632                sort_by_nse=0,633                phonotactics_filter=True,634                ) == "^k i h e$|^k o h e$|^h i h e$|^h o h e$"635    # assert 4 calls: tokenise, read_sc, and get_nse, nlargest636    prosodic_string_mock.assert_has_calls([call(list(i)) for i in [637    "kihe", "kohe", "hihe", "hohe"638    ]])639    nlargest_mock.assert_not_called()640    assert monkey_adrc.read_sc_called_with == [641        (['#-', '#k', 'i', 'k', 'i#', '-#'], 9999999)]642    assert monkey_adrc.get_nse_called_with == []643    del monkey_adrc, AdrcMonkeyReconstruct644def test_repair_phonotactics():645    """test if phonotactic structures are adapted correctly"""646    # set up mock class, used multiple times throughout this test647    class AdrcMonkeyrepair_phonotactics:648        def __init__(self):649            self.rank_closest_phonotactics_returns = "CVC, CVCCV"650            self.rank_closest_phonotactics_called_with = []651        def rank_closest_phonotactics(self, *args):652            self.rank_closest_phonotactics_called_with.append([*args])653            return self.rank_closest_phonotactics_returns654    # test all in dict655    # teardown/setup: overwrite mock class, plug in scdict_phonotactics,656    monkey_adrc = AdrcMonkeyrepair_phonotactics()657    monkey_adrc.scdict_phonotactics = {"CVCV": ["CVC", "CVCCV"]}658    # set up: define vars for side_effect of mock editops659    ops1 = ("keep C", "keep V", "keep C", "delete V")660    ops2 = ("keep C", "keep V", "insert C", "keep C", "keep V")661    # set up: mock tokenise, helpers.editops, helpers.apply_edit662    with patch("loanpy.adrc.prosodic_string") as prosodic_string_mock:663        prosodic_string_mock.return_value="CVCV"664        with patch("loanpy.adrc.editops", side_effect=[665                [ops1], [ops2]]) as editops_mock:666            with patch("loanpy.adrc.apply_edit", side_effect=[667                    "k i k", "k i C k i"]) as apply_edit_mock:668                # assert repair_phonotactics is working669                assert Adrc.repair_phonotactics(670                    self=monkey_adrc,671                    ipastr=("k i k i", "CVCV"),672                    max_repaired_phonotactics=2) == [673                    'k i k',674                    'k i C k i']675    # assert 5 calls were made: word2phonotactics, rank_closest_phonotactics,676    # editops, apply_edit, tokenise677    prosodic_string_mock.assert_called_with == [678        [["k", "i", "k", "i"]]]679    assert monkey_adrc.rank_closest_phonotactics_called_with == []680    editops_mock.assert_has_calls(681        [call("CVCV", "CVC", 1, 100, 49), call("CVCV", "CVCCV", 1, 100, 49)])682    apply_edit_mock.assert_has_calls(683        [call(['k', 'i', 'k', 'i'], ops1),684         call(['k', 'i', 'k', 'i'], ops2)])685    # test struc missing from dict and rank_closest instead, test show_workflow686    # set up mock class, plug in empty dict to trigger error687    monkey_adrc = AdrcMonkeyrepair_phonotactics()688    monkey_adrc.scdict_phonotactics = {}689    monkey_adrc.workflow = OrderedDict()690    # set up: define side effect of mock-editops691    ops1 = ("keep C", "keep V", "keep C", "delete V")692    ops2 = ("keep C", "keep V", "insert C", "keep C", "keep V")693    # set up: mock tokenise, helpers.editops, helpers.apply_edit694    with patch("loanpy.adrc.editops", side_effect=[695            [ops1], [ops2]]) as editops_mock:696        with patch("loanpy.adrc.apply_edit", side_effect=[697                "k i k", "k i C k i"]) as apply_edit_mock:698                # assert repair_phonotactics is working699                assert Adrc.repair_phonotactics(700                    self=monkey_adrc,701                    ipastr=("k i k i", "CVCV"),702                    max_repaired_phonotactics=2,703                    show_workflow=True) == ['k i k', 'k i C k i']704    # assert 6 calls: word2phonotactics, rank_closest_phonotactics, workflow,705    # editops, apply_edit, tokenise706    prosodic_string_mock.assert_called_with == [707        [["k", "i", "k", "i"]]]708    assert monkey_adrc.rank_closest_phonotactics_called_with == [["CVCV", 2]]709    assert monkey_adrc.workflow == OrderedDict([710         ('predicted_phonotactics', "['CVC', 'CVCCV']")])711    editops_mock.assert_has_calls(712        [call("CVCV", "CVC", 1, 100, 49), call("CVCV", "CVCCV", 1, 100, 49)])713    apply_edit_mock.assert_has_calls(714        [call(['k', 'i', 'k', 'i'], ops1),715         call(['k', 'i', 'k', 'i'], ops2)])716    # tear down717    del monkey_adrc, ops1, ops2, AdrcMonkeyrepair_phonotactics718def test_adapt():719    """test if words are adapted correctly with sound correspondence data"""720    # set up mock class, used multiple times throughout this test.721    class AdrcMonkeyAdapt:722        def __init__(self, read_screturns=[723                [["k", "h"], ["e", "o"], ["k"]],724                [["k", "h"], ["e", "o"], ["t"], ["k"], ["e"]]],725                combineipalistsreturns=[726                "kek", "kok", "hek", "hok",727                "ketke", "kotke", "hetke", "hotke"]):728            self.repair_phonotactics_called_with = None729            self.read_sc_returns = iter(read_screturns)730            self.read_sc_called_with = []731            self.workflow = OrderedDict()732            self.inventories = {}733            self.inventories["CV_Segments"] = ["k", "h", "t.k", "o", "u", "e"]734            self.inventories["ProsodicStructure"] = ["CVCCV"]735            self.get_nse_returns = iter([(5, "bla"), (9, "bla")])736            self.get_nse_called_with = []737        def repair_phonotactics(self, *args):738            self.repair_phonotactics_called_with = [*args]739            self.workflow["donor_phonotactics"] = "CVCV"740            self.workflow["predicted_phonotactics"] = "['CVC', 'CVCCV']"741            return [['kik'], ['kiCki']]742        def read_sc(self, *args):743            self.read_sc_called_with.append([*args])744            return next(self.read_sc_returns)745        #def repair_harmony(self, *args):746        #    self.repair_harmony_called_with.append([*args])747        #    return [[['kBk'], ['kiCki']]]748        #def word2phonotactics(self, *args):749        #    self.word2phonotactics_called_with.append([*args])750        #    return next(self.word2phonotactics_returns)751        def get_nse(self, *args):752            self.get_nse_called_with.append([*args])753            return next(self.get_nse_returns)754    # basic settings755    # create instance of mock class, mock tokenise, mock get_howmany756    monkey_adrc = AdrcMonkeyAdapt()757    with patch("loanpy.adrc.get_howmany") as get_howmany_mock:758        with patch("loanpy.adrc.combine_ipalists"759                   ) as combine_ipalists_mock:760            with patch("loanpy.adrc.repair_harmony"761                   ) as repair_harmony_mock:762                combine_ipalists_mock.return_value = [763                    "k e k", "k o k", "h e k", "h o k",764                    "k e t k e", "k o t k e", "h e t k e", "h o t k e"]765                get_howmany_mock.return_value = (8, 1, 1)766                # assert adapt is working767                assert Adrc.adapt(768                    self=monkey_adrc,769                    ipastr=("k i k i", "CVCV"),770                    howmany=8771                    ) == "k e k, k o k, h e k, h o k, k e t k e, k o t k e, h e t k e, h o t k e"772    # assert 7 calls: tokenise, repair_phonotactics, read_sc, combine_ipalists,773    # repair_harmony, word2phonotactics, get_howmany774    combine_ipalists_mock.assert_called_with([775        [["k", "h"], ["e", "o"], ["k"]],776        [["k", "h"], ["e", "o"], ["t"], ["k"], ["e"]]])777    get_howmany_mock.assert_called_with(8, 0, 1)778    assert monkey_adrc.repair_phonotactics_called_with == [779        ("k i k i", "CVCV"), 1, 1, 100, 49, False]780    assert monkey_adrc.read_sc_called_with == [781        [['kik'], 8], [['kiCki'], 8]]782    repair_harmony_mock.assert_not_called()783    # advanced settings784    # teardown/setup: overwrite mock class, mock tokenise,785    # mock flatten, mock get_howmany786    monkey_adrc = AdrcMonkeyAdapt(read_screturns=[787        [["k", "h", "c"], ["o", "u"], ["k"]],788        [["k"], ["o", "u"], ["t", "d"], ["k"], ["e"]]])789    with patch("loanpy.adrc.flatten") as flatten_mock:790        flatten_mock.return_value = [list('kBk'), list('kiCki')]791        with patch("loanpy.adrc.repair_harmony") as repair_harmony_mock:792            repair_harmony_mock.return_value = [[['kBk'], ['kiCki']]]793            with patch("loanpy.adrc.get_howmany") as get_howmany_mock:794                get_howmany_mock.return_value = (2, 2, 2)795                with patch("loanpy.adrc.combine_ipalists"796                           ) as combine_ipalists_mock:797                    combine_ipalists_mock.return_value = [798                        'k o k', 'k u k', 'h o k', 'h u k', 'c o k',799                        'c u k', 'k o t k e', 'k o d k e', 'k u t k e', 'k u d k e']800                    with patch("loanpy.adrc.prosodic_string",801                        side_effect=["CVC"] * 6 + ["CVCCV"] * 4) as prosodic_string_mock:802                        with patch("loanpy.adrc.get_clusters",803                        side_effect=[804                                'k o t.k e', 'k o d.k e', 'k u t.k e',805                                'k u d.k e']) as get_clusters_mock:806                            with patch("loanpy.adrc.nlargest") as nlargest_mock:807                                nlargest_mock.return_value = [(9, "k u t k e"),808                                (5, "k o t k e")]809                                # assert adapt works810                                assert Adrc.adapt(811                                    self=monkey_adrc,812                                    ipastr=("k i k i", "CVCV"),813                                    howmany=6,814                                    max_repaired_phonotactics=2,815                                    max_paths2repaired_phonotactics=2,816                                    repair_vowelharmony=True,817                                    phonotactics_filter=True,818                                    sort_by_nse=9999999,819                                    cluster_filter=True,820                                    show_workflow=True) == "k u t k e, k o t k e"821    # assert 8 calls: tokenise, flatten, repair_phonotactics, read_sc,822    # combine_ipalists, repair_harmony, workflow, get_howmany823    get_howmany_mock.assert_called_with(6, 2, 2)824    combine_ipalists_mock.assert_called_with([825        [["k", "h", "c"], ["o", "u"], ["k"]], [["k"],826                                               ["o", "u"],827                                               ["t", "d"], ["k"], ["e"]]])828    assert list(flatten_mock.call_args_list[0][0][0]) == [829        [[['kBk'], ['kiCki']]], [[['kBk'], ['kiCki']]]]830    assert monkey_adrc.repair_phonotactics_called_with == [831        ("k i k i", "CVCV"), 2, 2, 100, 49, True]832    assert monkey_adrc.read_sc_called_with == [833        [["k", "B", "k"], 2], [["k", "i", "C", "k", "i"], 2]]834    repair_harmony_mock.assert_has_calls([835        call(['kik']), call(['kiCki'])])836    assert monkey_adrc.get_nse_called_with == [837        ['k i k i', 'k o t k e'], ['k i k i', 'k u t k e']]838    assert monkey_adrc.workflow == OrderedDict(839        [   ('donor_phonotactics', 'CVCV'), ('predicted_phonotactics',840                                          "['CVC', 'CVCCV']"),841            ('adapted_phonotactics', "[['kik'], ['kiCki']]"),842            ('adapted_vowelharmony',843             "[['k', 'B', 'k'], ['k', 'i', 'C', 'k', 'i']]"),844            ('before_combinatorics',845             "[[['k', 'h', 'c'], ['o', 'u'], ['k']], \846[['k'], ['o', 'u'], ['t', 'd'], ['k'], ['e']]]")])847    prosodic_string_mock.assert_has_calls([call(i) for i in [848        ['k', 'o', 'k'], ['k', 'u', 'k'], ['h', 'o', 'k'],849        ['h', 'u', 'k'], ['c', 'o', 'k'],850        ['c', 'u', 'k'], ['k', 'o', 't', 'k', 'e'],851        ['k', 'o', 'd', 'k', 'e'], ['k', 'u', 't', 'k', 'e'],852        ['k', 'u', 'd', 'k', 'e']]])853    # phonotactics_filter empty854    # teardown/setup: overwrite instance of mock class,855    # plug in phonotactic_inventory, mock tokenise856    monkey_adrc = AdrcMonkeyAdapt()857    monkey_adrc.inventories["ProsodicStructure"] = ["CV", "VC"]858    with patch("loanpy.adrc.get_howmany") as get_howmany_mock:859        get_howmany_mock.return_value = (1, 1, 1)860        with patch("loanpy.adrc.combine_ipalists"861                   ) as combine_ipalists_mock:862            combine_ipalists_mock.return_value = [863                'k o k', 'k u k', 'h o k', 'h u k', 'c o k',864                'c u k', 'k o t k e', 'k o d k e', 'k u t k e', 'k u d k e']865            # assert adapt returns error message as string866            assert Adrc.adapt(867                self=monkey_adrc, ipastr=("k i k i", "CVCV"),868                phonotactics_filter=True869            ) == "wrong phonotactics"870    # assert 4 calls: tokenise, repair_phonotactics,871    # read_sc and combine_ipalists872    get_howmany_mock.assert_called_with(1, 0, 1)873    combine_ipalists_mock.assert_called_with([874        [["k", "h"], ["e", "o"], ["k"]], [["k", "h"],875                                          ["e", "o"], ["t"], ["k"], ["e"]]])876    assert monkey_adrc.repair_phonotactics_called_with == [877        ("k i k i", "CVCV"), 1, 1, 100, 49, False]878    assert monkey_adrc.read_sc_called_with == [879        [['kik'], 1], [['kiCki'], 1]]880    # cluster_filter empty filter881    # teardown/setup: overwrite instance of mock class882    # , plug in cluster_inventory, mock tokenise883    monkey_adrc = AdrcMonkeyAdapt()884    monkey_adrc.inventories["CV_Segments"] = ["p.r", "g.r", "v.r.p", "s.k.r.r.r.r"]885    with patch("loanpy.adrc.get_howmany") as get_howmany_mock:886        get_howmany_mock.return_value = (1, 1, 1)887        with patch("loanpy.adrc.combine_ipalists"888                   ) as combine_ipalists_mock:889            combine_ipalists_mock.return_value = [890                'k o k', 'k u k', 'h o k', 'h u k', 'c o k',891                'c u k', 'k o t k e', 'k o d k e', 'k u t k e', 'k u d k e']892            # make sure adapt works (i.e. returns error message as string)893            assert Adrc.adapt(894                self=monkey_adrc, ipastr=("k i k i", "CVCV"),895                cluster_filter=True896            ) == "wrong clusters"897    # assert 4 calls: tokenise, repair_phonotactics, read_sc, combine_ipalists898    get_howmany_mock.assert_called_with(1, 0, 1)899    combine_ipalists_mock.assert_called_with([900        [["k", "h"], ["e", "o"], ["k"]], [["k", "h"],901                                          ["e", "o"], ["t"], ["k"], ["e"]]])902    assert monkey_adrc.repair_phonotactics_called_with == [903        ("k i k i", "CVCV"), 1, 1, 100, 49, False]904    assert monkey_adrc.read_sc_called_with == [905        [['kik'], 1], [['kiCki'], 1]]906    # advanced settings, sort_by_nse=1907    # teardown/setup: overwrite mock class, mock tokenise,908    # mock flatten, mock get_howmany909    monkey_adrc = AdrcMonkeyAdapt(read_screturns=[910        [["k", "h", "c"], ["o", "u"], ["k"]],911        [["k"], ["o", "u"], ["t", "d"], ["k"], ["e"]]])912    with patch("loanpy.adrc.flatten") as flatten_mock:913        flatten_mock.return_value = [list('kBk'), list('kiCki')]914        with patch("loanpy.adrc.repair_harmony") as repair_harmony_mock:915            repair_harmony_mock.return_value = [[['kBk'], ['kiCki']]]916            with patch("loanpy.adrc.get_howmany") as get_howmany_mock:917                get_howmany_mock.return_value = (2, 2, 2)918                with patch("loanpy.adrc.combine_ipalists"919                           ) as combine_ipalists_mock:920                    combine_ipalists_mock.return_value = [921                        'k o k', 'k u k', 'h o k', 'h u k', 'c o k',922                        'c u k', 'k o t k e', 'k o d k e', 'k u t k e', 'k u d k e']923                    with patch("loanpy.adrc.prosodic_string",924                        side_effect=["CVC"] * 6 + ["CVCCV"] * 4):925                        with patch("loanpy.adrc.get_clusters",926                        side_effect=[927                                'k o t.k e', 'k o d.k e', 'k u t.k e',928                                'k u d.k e']) as get_clusters_mock:929                            with patch("loanpy.adrc.nlargest") as nlargest_mock:930                                nlargest_mock.return_value = [(9, "k u t k e")]931                                # assert adapt works932                                assert Adrc.adapt(933                                    self=monkey_adrc,934                                    ipastr=("k i k i", "CVCV"),935                                    howmany=6,936                                    max_repaired_phonotactics=2,937                                    max_paths2repaired_phonotactics=2,938                                    repair_vowelharmony=True,939                                    phonotactics_filter=True,940                                    sort_by_nse=1,941                                    cluster_filter=True,942                                    show_workflow=True) == "k u t k e, k o t k e"943    # assert 8 calls: tokenise, flatten, repair_phonotactics, read_sc,944    # combine_ipalists, repair_harmony, workflow, get_howmany945    get_howmany_mock.assert_called_with(6, 2, 2)946    combine_ipalists_mock.assert_called_with([947        [["k", "h", "c"], ["o", "u"], ["k"]], [["k"],948                                               ["o", "u"],949                                               ["t", "d"], ["k"], ["e"]]])950    nlargest_mock.assert_called_with(951        1, [(5, "k o t k e"), (9, "k u t k e")])952    assert list(flatten_mock.call_args_list[0][0][0]) == [953        [[['kBk'], ['kiCki']]], [[['kBk'], ['kiCki']]]]954    assert monkey_adrc.repair_phonotactics_called_with == [955        ("k i k i", "CVCV"), 2, 2, 100, 49, True]956    assert monkey_adrc.read_sc_called_with == [957        [["k", "B", "k"], 2], [["k", "i", "C", "k", "i"], 2]]958    repair_harmony_mock.assert_has_calls([959        call(['kik']), call(['kiCki'])])960    assert monkey_adrc.get_nse_called_with == [961        ['k i k i', 'k o t k e'], ['k i k i', 'k u t k e']]962    assert monkey_adrc.workflow == OrderedDict(963        [   ('donor_phonotactics', 'CVCV'), ('predicted_phonotactics',964                                          "['CVC', 'CVCCV']"),965            ('adapted_phonotactics', "[['kik'], ['kiCki']]"),966            ('adapted_vowelharmony',967             "[['k', 'B', 'k'], ['k', 'i', 'C', 'k', 'i']]"),968            ('before_combinatorics',969             "[[['k', 'h', 'c'], ['o', 'u'], ['k']], \970[['k'], ['o', 'u'], ['t', 'd'], ['k'], ['e']]]")])971    prosodic_string_mock.assert_has_calls([call(i) for i in [972        ['k', 'o', 'k'], ['k', 'u', 'k'], ['h', 'o', 'k'],973        ['h', 'u', 'k'], ['c', 'o', 'k'],974        ['c', 'u', 'k'], ['k', 'o', 't', 'k', 'e'],975        ['k', 'o', 'd', 'k', 'e'], ['k', 'u', 't', 'k', 'e'],976        ['k', 'u', 'd', 'k', 'e']]])977    # advanced settings, sort_by_nse=2978    # teardown/setup: overwrite mock class, mock tokenise,979    # mock flatten, mock get_howmany980    monkey_adrc = AdrcMonkeyAdapt(read_screturns=[981        [["k", "h", "c"], ["o", "u"], ["k"]],982        [["k"], ["o", "u"], ["t", "d"], ["k"], ["e"]]])983    with patch("loanpy.adrc.flatten") as flatten_mock:984        flatten_mock.return_value = [list('kBk'), list('kiCki')]985        with patch("loanpy.adrc.repair_harmony") as repair_harmony_mock:986            repair_harmony_mock.return_value = [[['kBk'], ['kiCki']]]987            with patch("loanpy.adrc.get_howmany") as get_howmany_mock:988                get_howmany_mock.return_value = (2, 2, 2)989                with patch("loanpy.adrc.combine_ipalists"990                           ) as combine_ipalists_mock:991                    combine_ipalists_mock.return_value = [992                        'k o k', 'k u k', 'h o k', 'h u k', 'c o k',993                        'c u k', 'k o t k e', 'k o d k e', 'k u t k e', 'k u d k e']994                    with patch("loanpy.adrc.prosodic_string",995                        side_effect=["CVC"] * 6 + ["CVCCV"] * 4):996                        with patch("loanpy.adrc.get_clusters",997                        side_effect=[998                                'k o t.k e', 'k o d.k e', 'k u t.k e',999                                'k u d.k e']) as get_clusters_mock:1000                            with patch("loanpy.adrc.nlargest") as nlargest_mock:1001                                nlargest_mock.return_value = [(9, "k u t k e"),1002                                (5, "k o t k e")]1003                                # assert adapt works1004                                assert Adrc.adapt(1005                                    self=monkey_adrc,1006                                    ipastr=("k i k i", "CVCV"),1007                                    howmany=6,1008                                    max_repaired_phonotactics=2,1009                                    max_paths2repaired_phonotactics=2,1010                                    repair_vowelharmony=True,1011                                    phonotactics_filter=True,1012                                    sort_by_nse=2,1013                                    cluster_filter=True,1014                                    show_workflow=True) == "k u t k e, k o t k e"1015    # assert 8 calls: tokenise, flatten, repair_phonotactics, read_sc,1016    # combine_ipalists, repair_harmony, workflow, get_howmany1017    get_howmany_mock.assert_called_with(6, 2, 2)1018    combine_ipalists_mock.assert_called_with([1019        [["k", "h", "c"], ["o", "u"], ["k"]], [["k"],1020                                               ["o", "u"],1021                                               ["t", "d"], ["k"], ["e"]]])1022    nlargest_mock.assert_called_with(2, [1023        (5, "k o t k e"), (9, "k u t k e")])1024    assert list(flatten_mock.call_args_list[0][0][0]) == [1025        [[['kBk'], ['kiCki']]], [[['kBk'], ['kiCki']]]]1026    assert monkey_adrc.repair_phonotactics_called_with == [1027        ("k i k i", "CVCV"), 2, 2, 100, 49, True]1028    assert monkey_adrc.read_sc_called_with == [1029        [["k", "B", "k"], 2], [["k", "i", "C", "k", "i"], 2]]1030    repair_harmony_mock.assert_has_calls([1031        call(['kik']), call(['kiCki'])])1032    assert monkey_adrc.get_nse_called_with == [1033        ['k i k i', 'k o t k e'], ['k i k i', 'k u t k e']]1034    assert monkey_adrc.workflow == OrderedDict(1035        [   ('donor_phonotactics', 'CVCV'), ('predicted_phonotactics',1036                                          "['CVC', 'CVCCV']"),1037            ('adapted_phonotactics', "[['kik'], ['kiCki']]"),1038            ('adapted_vowelharmony',1039             "[['k', 'B', 'k'], ['k', 'i', 'C', 'k', 'i']]"),1040            ('before_combinatorics',1041             "[[['k', 'h', 'c'], ['o', 'u'], ['k']], \1042[['k'], ['o', 'u'], ['t', 'd'], ['k'], ['e']]]")])1043    prosodic_string_mock.assert_has_calls([call(i) for i in [1044        ['k', 'o', 'k'], ['k', 'u', 'k'], ['h', 'o', 'k'],1045        ['h', 'u', 'k'], ['c', 'o', 'k'],1046        ['c', 'u', 'k'], ['k', 'o', 't', 'k', 'e'],1047        ['k', 'o', 'd', 'k', 'e'], ['k', 'u', 't', 'k', 'e'],1048        ['k', 'u', 'd', 'k', 'e']]])1049    # tear down1050    del monkey_adrc, AdrcMonkeyAdapt1051def test_get_nse():1052    """test if normalised sum of examples is calculated correctly"""1053    # test first break, no set up needed here1054    assert Adrc.get_nse(self=None, left=None, right=None) == (0, 0, [0], [])1055    # create mock class, used multiple times in this test1056    class AdrcMonkeyget_nse:1057        def __init__(self):1058            self.align_called_with = []1059            self.sedict = {1060                "#-<*-": 5,1061                "#É<*j": 6,1062                "É<*É": 7,1063                "l<*l.k": 8,1064                "o<*É": 9}1065            self.probdict = {1066                "#-<*-": 1,1067                "#É<*j": 1,1068                "É<*É": 1,1069                "l<*l.k": 1,1070                "o<*É": 1}1071            self.edict = {"#-<*-": [1, 2], "#É<*j": [3, 4],1072                          "É<*É": [5], "l<*l.k": [6, 7, 8], "o<*É": [9]}1073            self.connector = "<*"1074            self.adapting = False1075        def align_clusterwise(self, *args):1076            self.align_called_with.append([*args])1077            return DataFrame({"keys": ['#-', '#É', 'É', 'l', 'o', 'É¡#'],1078                              "vals": ['-', 'j', 'É', 'l.k', 'É', '-']})1079    # test default settings (normalised sum of examples)1080    # set up instance of mock class1081    monkey_adrc = AdrcMonkeyget_nse()1082    # assert1083    assert Adrc.get_nse(1084        self=monkey_adrc, left="É É l o É¡", right="j É l.k É") == (1085        5.83, 35, '[5, 6, 7, 8, 9, 0]', float("inf"), '[1, 1, 1, 1, 1, 0]',1086        "['#-<*-', '#É<*j', 'É<*É', 'l<*l.k', 'o<*É', 'É¡#<*-']")1087    # assert call1088    assert monkey_adrc.align_called_with == [["É É l o É¡", "j É l.k É"]]1089    # tear down mock class instance...move_a_ball.py
Source:move_a_ball.py  
1import pygame2import numpy as np3pygame.init()4#perminants5screen_height = 6006screen_width = 10007ground_height = 1508ground_x = 09ground_y = screen_height-ground_height10daynight = 111#colors12moon_color = (100,100,200)13printer_color = (200,100,100)14skirt_color = (200,100,200)15bak1_color = (130,0,130)16ground_color = (80,0,0)17black = (0,0,0)18monkey_color = (150,150,150)19#characters demensions20printer_width = 5021skirt_height = 3022printer_height = 2023printer_skirt = printer_width*0.3024monkey_width = 1025monkey_height = 1026#character positions27printer_x = (screen_width-printer_width)*0.528printer_y = ground_y-skirt_height/229monkey_x = [0,0,0,0]30monkey_y = [0,0,0,0]31monkey_ang = [0,0,0,0]32for i in range(4):33    monkey_x[i] = screen_width/234    monkey_y[i] = ground_y+0.5*ground_height-0.5*monkey_height35#printer stats36power = 037#background movement start postion38moon_y = screen_height39moon_x = 80040#ball start demensions41moon_radius = 3042moon_wall = 3043count = 044rund = []45bak_color = bak1_color46test = []47#main game48run = True49while run:50    pygame.display.set_caption('fineass')51    display = pygame.display.set_mode((screen_width,screen_height))52    53    game = True54    while game:55        #dellay and screen reset56        count = count+157        pygame.time.delay(30)58        display.fill(bak_color)59        60        #moon orbit61        if count > 1:62            moon_y = moon_y-3*daynight63            moon_x = moon_x-164            count = 065        if moon_y < 0-moon_radius*1.5:66            daynight = -167            bak_color = bak1_color68        if moon_y > screen_height:69            daynight = 170            bak_color = bak1_color71        if moon_x-moon_radius < 0:72            daynight = 173        74        #sun set75        if moon_y+moon_radius < ground_y:76            bak_color = list(bak_color)77            bak_color[1] = int(bak_color[1]*np.absolute(moon_y/(screen_height/2)))78            if np.absolute(int(bak_color[2]*np.absolute(moon_y/(screen_height*2/3))))<255 and np.absolute(int(bak_color[2]*np.absolute(moon_y/(screen_height*2/3))))>0:79                bak_color[2] = np.absolute(int(bak_color[2]*np.absolute(moon_y/(ground_y))))80            if np.absolute(int(bak_color[0]*np.absolute(moon_y/(screen_height*2/3))))<255 and np.absolute(int(bak_color[0]*np.absolute(moon_y/(screen_height*2/3))))>0:81                bak_color[0] = int(bak_color[0]*np.absolute(moon_y/(ground_y+ground_height/2)))82            bak_color = tuple(bak_color)83        84        #charge when teh suns out85        if moon_y < ground_y:86            power = np.round(power+(moon_y/screen_height)*2)87        88        #monkeys89        for i in range(4):90            #random rotation91            monkey_ang[i] = monkey_ang[i] + (np.pi/4)*(np.random.random_sample()-0.5)92            93            #stay on the ground94            if monkey_y[i] <= ground_y:95                if monkey_ang[i] < np.pi*3/2:96                    monkey_ang[i] = np.pi/297                elif monkey_ang[i] > np.pi*3/2:98                    monkey_ang[i] = np.pi/299            100            #don't go to low101            if monkey_y[i] >= screen_height+monkey_height*5:102                if monkey_ang[i] < np.pi/2:103                    monkey_ang[i] = np.pi*3/2104                elif monkey_ang[i] > np.pi/2:105                    monkey_ang[i] = np.pi*3/2106                        107            #move based on rotation108            monkey_y[i] = monkey_y[i] + np.sin(monkey_ang[i])*4109            monkey_x[i] = monkey_x[i] + np.cos(monkey_ang[i])*4110            111            #lOOP:112            #angle113            if monkey_ang[i] <= 0:114                monkey_ang[i] = 2*np.pi115            elif monkey_ang[i] >= 2*np.pi:116                monkey_ang[i] = 0 117            #sides       118            if np.absolute(monkey_x[i]-(screen_width/2)) > (screen_width/2)+monkey_width*4:119                if monkey_x[i]-(screen_width/2) > 0:120                    monkey_x[i] = 0-monkey_width*2121                elif monkey_x[i]-(screen_width/2) < 0:122                    monkey_x[i] = screen_width+monkey_width*2123        124        #draw proscribed shapes125        if daynight == 1:126            pygame.draw.circle(display, moon_color, (moon_x, moon_y), moon_radius, moon_wall)127        pygame.draw.rect(display, ground_color, (ground_x, ground_y, screen_width, screen_height))128        points = [(printer_x-printer_skirt,printer_y+skirt_height),(printer_x+printer_width+printer_skirt,printer_y+skirt_height),(printer_x+printer_width,printer_y),(printer_x,printer_y)]129        pygame.draw.polygon(display, skirt_color, points)130        pygame.draw.rect(display, printer_color, (printer_x, printer_y, printer_width, printer_height))131        pygame.draw.rect(display, monkey_color, (monkey_x[0], monkey_y[0], monkey_width, monkey_height))132        pygame.draw.rect(display, monkey_color, (monkey_x[1], monkey_y[1], monkey_width, monkey_height))133        pygame.draw.rect(display, monkey_color, (monkey_x[2], monkey_y[2], monkey_width, monkey_height))134        pygame.draw.rect(display, monkey_color, (monkey_x[3], monkey_y[3], monkey_width, monkey_height))135        136        OUT = 'power:  '+str(power)+'V moon_y: '+str(moon_y)137        font = pygame.font.Font('freesansbold.ttf', 12) 138        text = font.render(OUT, True, printer_color, bak_color)139        textRect = text.get_rect()140        textRect.center = (screen_width//2, screen_height//2)141        display.blit(text, textRect)142        143        #make the game quit properly144        pygame.display.update()145        146        for event in pygame.event.get() :  147                    if event.type == pygame.QUIT : 148                        pygame.quit() 149                        quit() 150                    pygame.display.update()...017.monkeyrunner记录.py
Source:017.monkeyrunner记录.py  
1#coding:utf-82#from com.android.monkeyrunner import MonkeyRunner as mr,MonkeyDevice as md,MonkeyImage as mk 3from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice,MonkeyImage4#è¿æ¥å½å设å¤ï¼è¿åä¸ä¸ªMonkeyDevice对象ï¼Pä¸ºç©ºå°±æ¯æ éçå¾
5#device=mr.waitForConnection()6#P1çå¾
æ¶é´ï¼P2设å¤ID7#device=MonkeyRunner.waitForConnection(5,"e45e9655")8device=MonkeyRunner.waitForConnection(1)9package="com.android.settings"10activity="com.android.settings.Settings"11print(device)12if device==None:13	print("Failed,please try again")14else:15	print("It's OK")16#æ é¢æ å®½åº¦17y0=12018#permission1ç宽度19y1=11020#appç宽度21y2=9022#device.touch(By.id("id/more"),MonkeyDevice.DOWN_AND_UP)23#è¾å
¥1234524#device.type("12345")25#触æ¸åæ +å¨ä½26#ç¹å»Apps27device.touch(300,540,MonkeyDevice.DOWN_AND_UP)28MonkeyRunner.sleep(2)29#ç¹å»å³ä¸è§30device.touch(390,80,MonkeyDevice.DOWN_AND_UP)31MonkeyRunner.sleep(2)32#ç¹å»App permissions33device.touch(300,170,MonkeyDevice.DOWN_AND_UP)34MonkeyRunner.sleep(2)35#æé1ï¼36#ç¹å»Body sensors37device.touch(300,80+y1,MonkeyDevice.DOWN_AND_UP)38MonkeyRunner.sleep(2)39#ç¹å»å³ä¸è§40device.touch(450,80,MonkeyDevice.DOWN_AND_UP)41MonkeyRunner.sleep(2)42#ç¹å»Show system43device.touch(290,80,MonkeyDevice.DOWN_AND_UP)44MonkeyRunner.sleep(2)45#è¿å46device.press("KEYCODE_BACK",MonkeyDevice.DOWN_AND_UP)47MonkeyRunner.sleep(2)48#æé2ï¼49#ç¹å»Calendar50device.touch(300,80+y1*2,MonkeyDevice.DOWN_AND_UP)51MonkeyRunner.sleep(2)52#ç¹å»å³ä¸è§53device.touch(450,80,MonkeyDevice.DOWN_AND_UP)54MonkeyRunner.sleep(2)55#ç¹å»Show system56device.touch(290,80,MonkeyDevice.DOWN_AND_UP)57MonkeyRunner.sleep(2)58y=[80+y2*2,80+y2*3,80+y2*5,80+y2*8,840]59for i in y:60	device.touch(300,i,MonkeyDevice.DOWN_AND_UP)61	MonkeyRunner.sleep(2)62	63#æé3ï¼64#ç¹å»Cemera65#æpoweré®66#device.press("KEYCODE_POWER",MonkeyDevice.DOWN_AND_UP)67#è¾å
¥A68#device.press("KEYCODE_A",MonkeyDevice.DOWN_AND_UP)	69#ä¸é³éé®70#device.press("KEYCODE_VOLUME_UP",MonkeyDevice.DOWN_AND_UP)	71#ä¸é³éé®72#device.press("KEYCODE_VOLUME_DOWN",MonkeyDevice.DOWN_AND_UP)	73#è¿å
¥è®¾ç½®çé¢74#device.startActivity(component=package+"/"+activity)75#çå¾
5ç§76#MonkeyRunner.sleep(5)77#æ»å¨78#device.drag((0,0),(200,600),0.5,10)79#è¾å
¥0-980#device.press("KEYCODE_0",MonkeyDevice.DOWN_AND_UP)81#device.press("KEYCODE_1",MonkeyDevice.DOWN_AND_UP)82#æè¿åé®83#device.press("KEYCODE_BACK",MonkeyDevice.DOWN_AND_UP)84#æHOMEé®85#device.press("KEYCODE_HOME",md.DOWN_AND_UP)86#æèåé®87#device.press("KEYCODE_MENU",MonkeyDevice.DOWN)88#æªå±89#result = device.takeSnapshot()90#ä¿åå°Fçï¼åå为result1.pngï¼æ ¼å¼ä¸ºpng...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
