Skip to content

Add probe_ports method to LiveServerTestCase #3

@rouilj

Description

@rouilj

When testing Roundup, I had a chicken and egg problem. I needed to know what port was going to be used
by Roundup running as a wsgi application so I could embed it in the config file. However I couldn't get that port
until I started Roundup.

As a workaround I hardcoded port_range = (9001, 9001) and used that throughout my test. Which worked for
my system, but others had issues when they had something running at port 9001.

I have added the following method to wsgi_liveserver.py to allow probing for an open port.
(ed: replaced code. It didn't work like I intended as it was missing a loop.)

    def probe_ports(cls, start=port_range[0], end=port_range[1]):

        port = start

        while port <= end:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

            try:
                s.connect(('127.0.0.1', port))
            except socket.error as e:
                if not hasattr(e, 'args') or e.args[0] != errno.ECONNREFUSED:
                    raise
                return port
            else:
                s.close()
                port += 1

        return None

In addition to this you need to add import errno at the top of the file with the other imports.

An example use of this method is:

import pytest
from .wsgi_liveserver import LiveServerTestCase

class WsgiSetup(LiveServerTestCase):
    tracker_port = LiveServerTestCase.probe_ports(8080, 8100)
    if tracker_port is None:
        pytest.skip("Unable to find available port for server: 8080-8100",
                    allow_module_level=True)
    port_range = (tracker_port, tracker_port)

    # set a couple of properties to use for URL generation in
    # expected output or use to set TRACKER_WEB in config.ini.
    tracker_web = "http://localhost:%d/" % tracker_port
       # tracker_web_base should be the same as self.base_url()
    tracker_web_base = "http://localhost:%d" % tracker_port

Hopefully this will be useful to others.

Thanks again for making this module it has been very useful in testing Roundup.

-- rouilj

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions