Search code examples
pythoncookiesautomated-testssplinter

Assert value for key in cookie dict


I've just started working with python test automation, and I'm trying to assert that a certain cookie with a certain value is being set when clicking on a certain button. I'm automating tests using splinter, and so far I have this:

cookie_bar = browser.find_link_by_text('Yes')
manage_cookies = browser.find_link_by_text('Manage cookies')
    if not manage_cookies:
        if cookie_bar:
            browser.find_link_by_text('Yes').first.click()
        else:
            browser.find_link_by_text('Hide this message').first.click()
    if manage_cookies:
            browser.find_link_by_text('Manage cookies').first.click()
            browser.driver.switch_to_window(browser.windows[-1].name)
            browser.find_by_text('Accept Cookies').first.click()
            browser.driver.switch_to_window(browser.windows[-1].name)
            cookies_list = browser.cookies.all()

The "browser.cookies.all()" method returns a dict of {'cookie1': 'value1', 'cookie2': 'value2', etc.}; I'm trying to assert that "cookie1" comes back with value "value1", but so far nothing I've tried has worked, as they all come with some sort of "unhashable" error:

assert ['cookie1' == 'value1'] in cookies_list # TypeError: unhashable type: 'list'
assert [{'cookie1': 'value1'}] in cookies_list # TypeError: unhashable type: 'list'
assert {'cookie1': 'value1'} in cookies_list # TypeError: unhashable type: 'dict'
assert {'cookie1', 'value1'} in cookies_list #TypeError: unhashable type: 'set'

Now, I've never worked with python before, so maybe it's something really simple that's escaping me, but I can't for the life of me figure it out. I can assert them individually, but what I really need is, in the simplest terms:

assert 'cookie1' with value 'value1' in cookies_list

Is there a way to do that?


Solution

  • You are saying that browser.cookies.all() return a dict, therefore, you should use it as a dict and not as a list.

    For example you can do:

    assert cookies_list.get('cookie1', None) == 'value1'
    

    Find some more info about dictionary here

    To check multiples values: Create another dict we the expected values:

    expected = {'cookie1': 'value1', 'cookie2': 'value2'}
    

    Edit to improve answer: And then iterate on all keys of the dict.

    for key in expected.keys():
        assert cookies_list.get(key, None) == expected[key]