How to dynamically add functionalities to the Browser

Suppose you want to add a login function to the Browser.


In [ ]:
from marigoso import Test
test = Test()
browser = test.launch_browser("Firefox")
data = {
    'url': "http://pytest.uk",
    'username': "myusername",
    'password': "mysecret"
}

You can define such a function at any point in your testbook. Note that you need to use self inside your function definition rather than using the word browser.


In [ ]:
def login(self, data):
    self.get_url(data['url'])
    if self.is_available('name=credential_0', 1):
        self.kb_type('name=credential_0', data['username'])
        self.kb_type('name=credential_1', data['password'])
        self.submit_btn('Login')
    assert self.is_available("Logout")
    return self.get_element("id=logged_in_user").text

Once defined, you can call the register_function method of test object to attach the function to the browser object.


In [1]:
test.register_function("browser", [login])

You can then confirm that the login is now a bound method of browser and can be used right away just like any other methods bound to browser.


In [4]:
browser.login


Out[4]:
<bound method login of <marigoso.test.Mixin (session="d000cb53-c0d9-4c4f-9c86-ec13350d760f")>>

In fact, using the same "register_function" method of the test object, you can dynamically attach functions to any attributes of test. The "register_function" accepts a list of functions as an argument so you can register multiple functions at once. And when you have a lot of these function extensions, you can group and organize them inside a class using the "register_classes" method of the test object.