Search code examples
pythonplaywrightplaywright-python

How to expect count bigger or smaller than?


Using Playwright and Python, how can I expect for count bigger or smaller than?

For example, this code expect for count of 2.

How do I achieve count >= 2 (Only bigger)

expect(self.page.locator('MyLocator')).to_have_count(2, timeout=20 * 1000)

Solution

  • This doesn't seem to be possible in the current Python Playwright API, but you could use wait_for_function as a workaround:

    page.wait_for_function("document.querySelectorAll('.foo').length > 2")
    

    This is web-first and will wait for the predicate, but the error message once it throws won't be as clear as the expect failure.

    If the count is immediately available and you don't need to wait for the predicate to be true, assert is useful to mention as another possibility:

    assert page.locator(".foo").count() > 2
    

    If you're using unittest, you can replace assert with, for example

    self.assertGreaterEqual(page.locator(".foo").count(), 2)
    self.assertGreater(page.locator(".foo").count(), 2)  # or
    

    Yet another workaround if you're dealing only with small numbers of elements:

    page.locator(".foo")
    expect(loc).not_to_have_count(0)
    expect(loc).not_to_have_count(1)
    expect(loc).not_to_have_count(2)
    

    Here, we ensure the count is greater than 2 by process of elimination. It's impossible for count to be less than 0, so we need not include that.

    You could do this for less than as well, but not as easily, and using a reasonable assumption that there'll never be more than, say, 20 or 50 elements in any conceivable run:

    loc = page.locator(".foo")
    for i in range(2, 20):
        expect(loc).not_to_have_count(i)
    

    This ensures the count is 0 or 1, or greater than some reasonably high upper-bound.