Skip to content

Question for write a Test with pytest in Plone #16

@1letter

Description

@1letter

@davisagli @ericof
Where is the best place for questions about pytest-plone? here or the community forum?

I play a little bit with the new pytest layer in an addon created with cookieplone

My goal: a functional test setup in a class with some sample content:

With the following setup all is fine. but the fixture is firing up in every method of my TestMyView class. This is not what i want. as far as I understand it, the reason is the scope of the fixture. in this case the "function scope".

# conftest.py

# global fixture to provide base structure for content
# can use in tests
@pytest.fixture
def contents_payload() -> list:
    """Payload to create two content items."""
    return [
        {
            "type": "Folder",
            "id": "test-folder",
            "title": "Test Folder",
            "description": "A Test Folder",
        },
        {
            "type": "Document",
            "id": "test-doc",
            "title": "Test Document",
            "description": "A Test Document",
        },
    ]

# fixture portal for functional test with test content
@pytest.fixture()
def portal(functional, content_payload):
    # the portal object for functional tests
    portal = functional["portal"]
    with api.env.adopt_roles(["Manager",]):
      for data in contents_payload:
        api.content.create(container=portal, **data)

    transaction.commit()
    return portal
# my Test Class
class TestMyView:
  def test_my_view1(self, portal):
    # do something in a functional test
    pass

  def test_my_view2(self, portal):
    # do something other stuff in a functional test
     pass

Now i changed the code to:

# fixture portal for functional test with test content
@pytest.fixture(scope="class")
def portal(functional_class, content_payload):
    # the portal object for functional tests
    portal = functional_class["portal"]
    with api.env.adopt_roles(["Manager",]):
      for data in contents_payload:
        api.content.create(container=portal, **data)

    transaction.commit()
    return portal

But this ends with an error:

self = <Layer 'collective.addon.testing.Collective.AddonLayer:FunctionalTesting'>, key = 'portal'

    def __getitem__(self, key):
        item = self.get(key, _marker)
        if item is _marker:
>           raise KeyError(key)
E           KeyError: 'portal'

.tox/test/lib/python3.12/site-packages/plone/testing/layer.py:28: KeyError

Where is my mistake? I thought, i can switch easily the scope, and no more changes are needed.

I'm new in the pytest world, please bear with me.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions