Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions aiosmtpd/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,10 @@ def _trigger_server(self):
# At this point, if self.hostname is Falsy, it most likely is "" (bind to all
# addresses). In such case, it should be safe to connect to localhost)
hostname = self.hostname or self._localhost
# If port is 0, we need to get the port that the OS assigned so that we
# can connect.
if self.port == 0:
self.port = self.server.sockets[0].getsockname()[1]
with ExitStack() as stk:
s = stk.enter_context(create_connection((hostname, self.port), 1.0))
if self.ssl_context:
Expand Down
1 change: 1 addition & 0 deletions aiosmtpd/docs/NEWS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Fixed/Improved
--------------
* All Controllers now have more rationale design, as they are now composited from a Base + a Mixin
* A whole bunch of annotations
* Allow using port=0 with TCP controllers to use an OS-assigned port (Closes #276).


1.4.4.post2 (2023-01-19)
Expand Down
9 changes: 9 additions & 0 deletions aiosmtpd/tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,15 @@ def test_hostname_none(self):
finally:
cont.stop()

def test_port_zero(self):
cont = Controller(Sink(), port=0)
try:
cont.start()
# Ensure port on controller has been populated with the OS-assigned port
assert cont.port != 0
finally:
cont.stop()

def test_testconn_raises(self, mocker: MockFixture):
mocker.patch("socket.socket.recv", side_effect=RuntimeError("MockError"))
cont = Controller(Sink(), hostname="")
Expand Down