调用自定义restCallTest方法触发WinError 10061问题求助
你遇到的这个情况确实有点费解——明明已经确认服务启动正常,直接在test方法里调用urlopen(self.restCall)完全没问题,但调用自己封装的restCallTest()方法就触发[WinError 10061] 由于目标计算机积极拒绝,无法建立连接的错误。先把你的两段代码清晰列出来,方便针对性分析:
正常运行的代码版本
class Test(testContainer): restcall = "http://localhost:8086/service/records/all" def __init__(self): # service is started in init, ... def restCallTest(self): getRecordsUrl = "http://localhost:8086/service/records/all" try: allRecordsResponse = urlopen(getRecordsUrl) except URLError as e: print(e.reason) return allRecordsResponse def test(self): response = urlopen(self.restCall)
报错的代码版本
class Test(testContainer): restcall = "http://localhost:8086/service/records/all" def __init__(self): # service is started in init, ... def restCallTest(self): getRecordsUrl = "http://localhost:8086/service/records/all" try: allRecordsResponse = urlopen(getRecordsUrl) except URLError as e: print(e.reason) return allRecordsResponse def test(self): response = self.restCallTest()
我来给你梳理几个最可能的排查方向:
线程/进程隔离问题
你提到服务是在__init__里启动的,有没有可能你的测试框架(比如unittest/pytest)或者testContainer基类,在运行测试方法时是在不同的线程或进程里执行的?直接在test里调用urlopen时,当前进程/线程能访问到__init__里启动的服务;但调用restCallTest()时,这个方法的执行上下文可能没连接到同一个服务实例,甚至服务在这个上下文里根本没启动。你可以在__init__和restCallTest()里分别加一行进程ID打印(import os; print(os.getpid())),对比两者的进程ID是否一致。初始化顺序与实例重复创建问题
有些测试框架会为每个测试方法重新实例化测试类,如果__init__里的服务启动逻辑有缺陷(比如重复启动时端口被占用却没正确处理,导致服务启动失败),那么第二次实例化时服务其实没真正运行,调用restCallTest()就会报错;而直接在test里调用时,可能刚好第一次实例化的服务还在运行。你可以在__init__里加日志,记录服务启动的状态、时间和端口占用情况,再对比报错时的时间点,确认服务是否真的在restCallTest()执行时处于运行状态。异常处理的隐藏逻辑问题
注意看你的restCallTest()方法:如果urlopen抛出URLError,你打印了错误原因但没有重新抛出异常,而是直接return allRecordsResponse——此时allRecordsResponse根本没被赋值,会触发UnboundLocalError,不过你说触发的是WinError 10061,所以这个可能不是直接原因,但不排除测试框架捕获了局部变量错误,却把之前的URLError暴露出来的情况。你可以修改异常处理逻辑试试:def restCallTest(self): getRecordsUrl = "http://localhost:8086/service/records/all" try: return urlopen(getRecordsUrl) except URLError as e: print(f"Error accessing {getRecordsUrl}: {e.reason}") raise # 重新抛出异常,让上层看到完整的错误栈localhost解析差异问题
虽然都是用localhost,但不同执行场景下可能存在解析差异——比如有些环境下localhost会优先解析到IPv6的::1,而你的服务只监听了IPv4的127.0.0.1。你可以把URL里的localhost换成127.0.0.1,看看restCallTest()调用是否恢复正常。
内容的提问来源于stack exchange,提问作者user9571515

