11from __future__ import annotations
22
3- import random
3+ import secrets
44import socket
55import string
66import sys
77import sysconfig
88from contextlib import closing
9+ from logging import getLogger
910from pathlib import Path
1011from subprocess import PIPE , Popen # ruff:ignore[suspicious-subprocess-import] # no shell, argument lists only
1112from threading import Thread
1213from typing import IO , TYPE_CHECKING , cast
1314
14- from ._index import Index , _check_call
15+ from ._command import check_call
16+ from ._index import Index
1517
1618if TYPE_CHECKING :
1719 from collections .abc import Iterator , Sequence
@@ -30,7 +32,8 @@ class IndexServer:
3032 def __init__ (
3133 self ,
3234 path : Path ,
33- with_root_pypi : bool = False , # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public parameter, changing it breaks callers
35+ # Preserve the public positional argument.
36+ with_root_pypi : bool = False , # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument]
3437 start_args : Sequence [str ] | None = None ,
3538 ) -> None :
3639 """
@@ -46,14 +49,14 @@ def __init__(
4649
4750 self .host = "localhost"
4851 with closing (socket .socket (socket .AF_INET , socket .SOCK_STREAM )) as socket_handler :
49- socket_handler .bind (("" , 0 ))
52+ socket_handler .bind (("" , 0 )) # devpi can bind to any IPv4 interface via start_args
5053 self .port = cast ("int" , socket_handler .getsockname ()[1 ])
51- self ._passwd = "" .join (random . choices (string .ascii_letters , k = 8 )) # ruff:ignore[suspicious-non-cryptographic-random-usage] # throwaway password of a test server
54+ self ._passwd = "" .join (secrets . choice (string .ascii_letters ) for _ in range ( 8 ))
5255
5356 scripts_dir = sysconfig .get_path ("scripts" )
5457 if scripts_dir is None :
55- msg = "could not get scripts folder of host interpreter" # pragma: no cover # typing guard
56- raise RuntimeError (msg ) # pragma: no cover # typing guard
58+ msg = "could not get scripts folder of host interpreter"
59+ raise RuntimeError (msg )
5760
5861 def _exe (name : str ) -> str :
5962 return str (Path (scripts_dir ) / f"{ name } { '.exe' if sys .platform == 'win32' else '' } " )
@@ -71,8 +74,12 @@ def _exe(name: str) -> str:
7174
7275 def __enter__ (self ) -> Self :
7376 """Start the index server."""
74- self ._create_and_start_server ()
75- self ._setup_client ()
77+ try :
78+ self ._create_and_start_server ()
79+ self ._setup_client ()
80+ except BaseException :
81+ self .__exit__ (None , None , None )
82+ raise
7683 return self
7784
7885 def _create_and_start_server (self ) -> None :
@@ -83,13 +90,13 @@ def _create_and_start_server(self) -> None:
8390 cmd .extend (("--role" , "standalone" , "--root-passwd" , self ._passwd ))
8491 if self ._with_root_pypi is False :
8592 cmd .append ("--no-root-pypi" )
86- _check_call (cmd )
93+ check_call (cmd )
8794 # 2. start the server
8895 cmd = [self ._server , "--serverdir" , server_at , "--port" , str (self .port )]
8996 cmd .extend (self ._start_args )
9097 self ._process = Popen (cmd , stdout = PIPE , universal_newlines = True ) # ruff:ignore[subprocess-without-shell-equals-true] # no shell, argument list only
9198 stdout = self ._drain_stdout ()
92- for line in stdout : # pragma: no branch # will always loop at least once
99+ for line in stdout :
93100 if "serving at url" in line :
94101
95102 def _keep_draining () -> None :
@@ -100,21 +107,24 @@ def _keep_draining() -> None:
100107 self ._stdout_drain = Thread (target = _keep_draining , name = "tox-test-stdout-drain" )
101108 self ._stdout_drain .start ()
102109 break
110+ else :
111+ msg = f"devpi server at { self ._server_dir } exited before it was ready"
112+ raise RuntimeError (msg )
103113
104114 def _drain_stdout (self ) -> Iterator [str ]:
105115 process = cast ("Popen[str]" , self ._process )
106116 stdout = cast ("IO[str]" , process .stdout )
107117 while True :
108- if process .poll () is not None : # pragma: no cover # a dead server is a failure path the tests do not drive
109- print ( f "devpi server with pid { process . pid } at { self . _server_dir } died") # ruff:ignore[print] # reports the dead server in the test output
118+ if process .poll () is not None :
119+ getLogger ( __name__ ). error ( "devpi server with pid %s at %s died" , process . pid , self . _server_dir )
110120 break
111121 yield stdout .readline ()
112122
113123 def _setup_client (self ) -> None :
114124 self ._client_dir .mkdir (exist_ok = True )
115125 base = ["--clientdir" , str (self ._client_dir )]
116- _check_call ([self ._client , "use" , * base , self .url ])
117- _check_call ([self ._client , "login" , * base , self .user , "--password" , self ._passwd ])
126+ check_call ([self ._client , "use" , * base , self .url ])
127+ check_call ([self ._client , "login" , * base , self .user , "--password" , self ._passwd ])
118128
119129 @property
120130 def url (self ) -> str :
@@ -139,9 +149,9 @@ def __exit__(
139149 :param exc_val: the exception leaving the block, or None
140150 :param exc_tb: traceback of that exception, or None
141151 """
142- if self ._process is not None : # pragma: no cover # defend against devpi startup fail
152+ if self ._process is not None :
143153 self ._process .terminate ()
144- if self ._stdout_drain is not None and self ._stdout_drain .is_alive (): # pragma: no cover # devpi startup fail
154+ if self ._stdout_drain is not None and self ._stdout_drain .is_alive ():
145155 self ._stdout_drain .join ()
146156
147157 def __repr__ (self ) -> str :
@@ -157,11 +167,11 @@ def create_index(self, name: str, *args: str) -> Index:
157167 :returns: the created index
158168 :raises ValueError: when an index with this name already exists
159169 """
160- if name in self ._indexes : # pragma: no cover # a duplicate name is a caller error the tests do not drive
170+ if name in self ._indexes :
161171 msg = f"index { name } already exists"
162172 raise ValueError (msg )
163173 base = [self ._client , "--clientdir" , str (self ._client_dir )]
164- _check_call ([* base , "index" , "-c" , name , * args ])
174+ check_call ([* base , "index" , "-c" , name , * args ])
165175 index = Index (f"{ self .url } /{ self .user } " , name , self .user , base )
166176 self ._indexes [name ] = index
167177 return index
0 commit comments