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 ._index import Index , check_call
1516
1617if TYPE_CHECKING :
1718 from collections .abc import Iterator , Sequence
@@ -30,7 +31,8 @@ class IndexServer:
3031 def __init__ (
3132 self ,
3233 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
34+ # Preserve the public positional argument.
35+ with_root_pypi : bool = False , # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument]
3436 start_args : Sequence [str ] | None = None ,
3537 ) -> None :
3638 """
@@ -46,14 +48,14 @@ def __init__(
4648
4749 self .host = "localhost"
4850 with closing (socket .socket (socket .AF_INET , socket .SOCK_STREAM )) as socket_handler :
49- socket_handler .bind (("" , 0 ))
51+ socket_handler .bind (("" , 0 )) # devpi can bind to any IPv4 interface via start_args
5052 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
53+ self ._passwd = "" .join (secrets . choice (string .ascii_letters ) for _ in range ( 8 ))
5254
5355 scripts_dir = sysconfig .get_path ("scripts" )
5456 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
57+ msg = "could not get scripts folder of host interpreter"
58+ raise RuntimeError (msg )
5759
5860 def _exe (name : str ) -> str :
5961 return str (Path (scripts_dir ) / f"{ name } { '.exe' if sys .platform == 'win32' else '' } " )
@@ -71,8 +73,12 @@ def _exe(name: str) -> str:
7173
7274 def __enter__ (self ) -> Self :
7375 """Start the index server."""
74- self ._create_and_start_server ()
75- self ._setup_client ()
76+ try :
77+ self ._create_and_start_server ()
78+ self ._setup_client ()
79+ except BaseException :
80+ self .__exit__ (None , None , None )
81+ raise
7682 return self
7783
7884 def _create_and_start_server (self ) -> None :
@@ -83,13 +89,13 @@ def _create_and_start_server(self) -> None:
8389 cmd .extend (("--role" , "standalone" , "--root-passwd" , self ._passwd ))
8490 if self ._with_root_pypi is False :
8591 cmd .append ("--no-root-pypi" )
86- _check_call (cmd )
92+ check_call (cmd )
8793 # 2. start the server
8894 cmd = [self ._server , "--serverdir" , server_at , "--port" , str (self .port )]
8995 cmd .extend (self ._start_args )
9096 self ._process = Popen (cmd , stdout = PIPE , universal_newlines = True ) # ruff:ignore[subprocess-without-shell-equals-true] # no shell, argument list only
9197 stdout = self ._drain_stdout ()
92- for line in stdout : # pragma: no branch # will always loop at least once
98+ for line in stdout :
9399 if "serving at url" in line :
94100
95101 def _keep_draining () -> None :
@@ -100,21 +106,24 @@ def _keep_draining() -> None:
100106 self ._stdout_drain = Thread (target = _keep_draining , name = "tox-test-stdout-drain" )
101107 self ._stdout_drain .start ()
102108 break
109+ else :
110+ msg = f"devpi server at { self ._server_dir } exited before it was ready"
111+ raise RuntimeError (msg )
103112
104113 def _drain_stdout (self ) -> Iterator [str ]:
105114 process = cast ("Popen[str]" , self ._process )
106115 stdout = cast ("IO[str]" , process .stdout )
107116 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
117+ if process .poll () is not None :
118+ getLogger ( __name__ ). error ( "devpi server with pid %s at %s died" , process . pid , self . _server_dir )
110119 break
111120 yield stdout .readline ()
112121
113122 def _setup_client (self ) -> None :
114123 self ._client_dir .mkdir (exist_ok = True )
115124 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 ])
125+ check_call ([self ._client , "use" , * base , self .url ])
126+ check_call ([self ._client , "login" , * base , self .user , "--password" , self ._passwd ])
118127
119128 @property
120129 def url (self ) -> str :
@@ -139,9 +148,9 @@ def __exit__(
139148 :param exc_val: the exception leaving the block, or None
140149 :param exc_tb: traceback of that exception, or None
141150 """
142- if self ._process is not None : # pragma: no cover # defend against devpi startup fail
151+ if self ._process is not None :
143152 self ._process .terminate ()
144- if self ._stdout_drain is not None and self ._stdout_drain .is_alive (): # pragma: no cover # devpi startup fail
153+ if self ._stdout_drain is not None and self ._stdout_drain .is_alive ():
145154 self ._stdout_drain .join ()
146155
147156 def __repr__ (self ) -> str :
@@ -157,11 +166,11 @@ def create_index(self, name: str, *args: str) -> Index:
157166 :returns: the created index
158167 :raises ValueError: when an index with this name already exists
159168 """
160- if name in self ._indexes : # pragma: no cover # a duplicate name is a caller error the tests do not drive
169+ if name in self ._indexes :
161170 msg = f"index { name } already exists"
162171 raise ValueError (msg )
163172 base = [self ._client , "--clientdir" , str (self ._client_dir )]
164- _check_call ([* base , "index" , "-c" , name , * args ])
173+ check_call ([* base , "index" , "-c" , name , * args ])
165174 index = Index (f"{ self .url } /{ self .user } " , name , self .user , base )
166175 self ._indexes [name ] = index
167176 return index
0 commit comments