Step 4: Implement tests for the File Server component with pytest

Let’s create a simple App with our File Server and File Server Test components.

Once the File Server is up and running, we’ll execute the test_file_server LightningWork and when both calls are successful, we exit the App using self._exit.

from lightning import LightningApp, LightningFlow


class Flow(LightningFlow):
    def __init__(self):
        super().__init__()
        # 1: Create a drive to share data between works
        self.drive = Drive("lit://file_server")
        # 2: Create  the filer server
        self.file_server = FileServer(self.drive)
        # 3: Create the file ser
        self.test_file_server = TestFileServer(self.drive)

    def run(self):
        # 1: Start the file server.
        self.file_server.run()

        # 2: Trigger the test file server work when ready.
        if self.file_server.alive():
            # 3 Execute the test file server work.
            self.test_file_server.run(self.file_server.url)
            self.test_file_server.run(self.file_server.url, first=False)

        # 4 When both execution are successful, exit the app.
        if self.test_file_server.num_successes == 2:
            self.stop()

    def configure_layout(self):
        # Expose the file_server component
        # in the UI using its `/` endpoint.
        return {"name": "File Server", "content": self.file_server}

Simply create a test.py file with the following code and run pytest tests.py:



def test_file_server():
    app = LightningApp(Flow())
    MultiProcessRuntime(app).dispatch()

To test the App in the cloud, create a cloud_test.py file with the following code and run pytest cloud_test.py. Under the hood, we are using the end-to-end testing playwright library, so you can interact with the UI.



def test_file_server_in_cloud():
    # You need to provide the directory containing the app file.
    app_dir = "docs/source-app/examples/file_server"
    with run_app_in_cloud(app_dir) as (admin_page, view_page, get_logs_fn, name):
        """# 1. `admin_page` and `view_page` are playwright Page Objects.

        # Check out https://playwright.dev/python/ doc to learn more.
        # You can click the UI and trigger actions.

        # 2. By calling logs = get_logs_fn(),
        # you get all the logs currently on the admin page.

        """

Test the application

Clone the Lightning repo and run the following command:

pytest docs/source/examples/file_server/app.py --capture=no -v

Tutorial


Find more examples