1- """providers Protocol contract 검증 — P-트랙 룰 1 게이트 + P-PR0 isinstance runtime.
1+ """providers Protocol contract 검증. P-트랙 룰 1 게이트 + P-PR0 isinstance runtime.
22
33dart/edgar/edinet 3 provider 가 동일 Protocol 표면 (DocsProvider · FinanceProvider ·
44FilingsProvider · MemorySafeProvider · CompanyProtocol) 만족하는지 검증.
55
6- P0.5 baseline: Protocol 일부는 아직 P1.5 에서 신설 — 미존재 시 xfail.
6+ P0.5 baseline: Protocol 일부는 아직 P1.5 에서 신설이라 미존재 시 xfail.
77P1.5 이후 strict: 모든 Protocol isinstance + 메서드 시그니처 introspection 일치.
8- P-PR0 (2026-05-12): 실 Company 인스턴스 isinstance runtime 검증 2 함수 추가 —
8+ P-PR0 (2026-05-12): 실 Company 인스턴스 isinstance runtime 검증 2 함수 추가.
99 baseline 모드 (현 위반 등록 + new violation 만 fail). P-PR8 strict 전환.
1010
1111게이트 활성화 단계:
12- P0.5 — Protocol import 시도, ImportError 면 xfail (회귀 가드만) — 완료
13- P1.5 — Protocol 신설 직후 isinstance 검증 활성 — 완료 (5 Protocol 실재)
14- P-PR0 — Company 인스턴스 + namespace isinstance baseline 모드 — 본 PR
15- P-PR8 — 전 contract strict (isinstanceRuntimeViolations / namespaceIsinstanceViolations 0)
12+ P0.5: Protocol import 시도, ImportError 면 xfail (회귀 가드만). 완료
13+ P1.5: Protocol 신설 직후 isinstance 검증 활성. 완료 (5 Protocol 실재)
14+ P-PR0: Company 인스턴스와 namespace isinstance baseline 모드. 본 PR
15+ P-PR8: 전 contract strict (isinstanceRuntimeViolations / namespaceIsinstanceViolations 0)
1616"""
1717
1818from __future__ import annotations
@@ -38,7 +38,7 @@ def _providerScope() -> tuple[str, ...]:
3838
3939
4040def _loadBaseline () -> dict :
41- """baseline JSON 로드. 없으면 빈 dict — 첫 실행은 회귀 가드 noop."""
41+ """baseline JSON 로드. 없으면 빈 dict 라 첫 실행은 회귀 가드 noop."""
4242 if _BASELINE .exists ():
4343 return json .loads (_BASELINE .read_text (encoding = "utf-8" ))
4444 return {"missingProtocols" : [], "missingProviderImpls" : [], "_note" : "P0.5 baseline" }
@@ -47,7 +47,7 @@ def _loadBaseline() -> dict:
4747def test_protocol_module_importable () -> None :
4848 """dartlab.core.protocols 가 import 가능해야 한다."""
4949 mod = importlib .import_module ("dartlab.core.protocols" )
50- assert hasattr (mod , "CompanyProtocol" ), "CompanyProtocol 부재 — core/protocols.py 손상"
50+ assert hasattr (mod , "CompanyProtocol" ), "CompanyProtocol 부재. core/protocols.py 손상"
5151
5252
5353def test_provider_protocols_present () -> None :
@@ -78,25 +78,28 @@ def test_provider_company_isinstance_baseline() -> None:
7878 from dartlab .core .protocols import CompanyProtocol
7979
8080 violations : list [str ] = []
81+ details : list [str ] = []
8182 for providerName in _providerScope ():
8283 try :
8384 mod = importlib .import_module (f"dartlab.providers.{ providerName } .company" )
84- if not hasattr (mod , "Company" ):
85- violations .append (f"{ providerName } : Company class 부재" )
86- continue
87- # isinstance 호출 가능성만 검증 (실 인스턴스 생성은 무거움 — 회귀 가드는 클래스 검증만)
88- CompanyCls = mod .Company
89- requiredAttrs = {"panel" , "select" , "trace" , "filings" }
90- missingAttrs = requiredAttrs - set (dir (CompanyCls ))
91- if missingAttrs :
92- violations .append (f"{ providerName } : { missingAttrs } 메서드 부재" )
93- except ImportError as exc :
94- violations .append (f"{ providerName } : import 실패 — { exc } " )
85+ except ImportError as error :
86+ violations .append (f"{ providerName } : import 실패" )
87+ details .append (f"{ providerName } : import 실패 ({ error } )" )
88+ continue
89+ if not hasattr (mod , "Company" ):
90+ violations .append (f"{ providerName } : Company class 부재" )
91+ continue
92+ # 클래스 표면만 본다. 실 인스턴스 생성은 무겁고 자료 유무를 탄다.
93+ companyCls = mod .Company
94+ requiredAttrs = {"panel" , "select" , "trace" , "filings" }
95+ missingAttrs = requiredAttrs - set (dir (companyCls ))
96+ if missingAttrs :
97+ violations .append (f"{ providerName } : { sorted (missingAttrs )} 메서드 부재" )
9598
9699 baseline = _loadBaseline ()
97100 allowed = set (baseline .get ("missingProviderImpls" , []))
98101 new_violations = set (violations ) - allowed
99- assert not new_violations , f"Provider Company contract 회귀: { new_violations } (baseline 외 신규)."
102+ assert not new_violations , f"Provider Company contract 회귀: { new_violations } (baseline 외 신규). { details } "
100103
101104
102105# ── P-PR0 추가: 실 인스턴스 isinstance runtime 검증 (baseline 모드) ──
@@ -112,35 +115,81 @@ def _providerProbes() -> tuple[tuple[str, str], ...]:
112115 return tuple ((provider , _PROBE_CODES [provider ]) for provider in _providerScope () if provider in _PROBE_CODES )
113116
114117
115- def test_company_isinstance_runtime () -> None :
116- """3 provider Company 인스턴스가 CompanyProtocol isinstance 만족 (baseline 모드).
118+ def _openCompany (providerName : str , stockCode : str , violations : list [str ], skipped : list [str ]):
119+ """Company 를 만들어 준다. 계약 위반과 환경 사정을 갈라 담는다.
120+
121+ 예전에는 생성 실패를 전부 violation 으로 적었고 그 문자열에 예외 메시지를 그대로 끼워
122+ 넣었다. baseline 대조가 그 문자열로 이뤄지므로 메시지가 한 글자만 달라져도 "baseline 밖
123+ 신규 위반" 이 됐다. 망 사정, 시간 초과, 속도 제한은 매번 다른 문장을 내므로 이 차단
124+ 게이트가 무작위로 빨간불이 됐다. 실제로 CI 에서 한 번 그렇게 났고 같은 커밋을 다시 돌리니
125+ 초록이었다.
126+
127+ Protocol 적합성은 구조 성질이지 자료 유무가 아니다. 그래서 생성자 계약이 어긋난
128+ 경우(TypeError)만 위반으로 적고, 그 밖의 실패는 건너뛴 사유로 적는다. 건너뛴 사유는
129+ 사람이 읽도록 남기되 baseline 대조에는 넣지 않는다.
117130
118- Protocol 5 종은 `core/protocols.py` 에 실재. 본 테스트는 *실 Company 인스턴스* 가
119- Protocol 의 `__instancecheck__` 를 통과하는지 검증.
131+ Args:
132+ providerName: provider 이름.
133+ stockCode: 탐침용 종목코드.
134+ violations: 계약 위반을 담을 목록. 안정된 key 만 들어간다.
135+ skipped: 환경 사정으로 못 본 것을 담을 목록.
120136
121- 인스턴스 생성 실패 (외부 의존 / 초기화 비용) 도 violation 으로 기록 — baseline 등록.
122- P-PR8 strict 전환 시 `isinstanceRuntimeViolations` 카운트 0 강제.
137+ Returns:
138+ Company 인스턴스. 못 만들었으면 None.
139+ """
140+ try :
141+ mod = importlib .import_module (f"dartlab.providers.{ providerName } .company" )
142+ except ImportError as exc :
143+ violations .append (f"{ providerName } : import 실패" )
144+ skipped .append (f"{ providerName } : import 실패 ({ type (exc ).__name__ } : { exc } )" )
145+ return None
146+ companyCls = getattr (mod , "Company" , None )
147+ if companyCls is None :
148+ violations .append (f"{ providerName } : Company class 부재" )
149+ return None
150+ try :
151+ return companyCls (stockCode )
152+ except TypeError as exc :
153+ # 생성자 서명이 계약과 어긋난다. 환경이 아니라 구현 문제다.
154+ violations .append (f"{ providerName } : 생성자 계약 위반" )
155+ skipped .append (f"{ providerName } : 생성자 계약 위반 ({ exc } )" )
156+ return None
157+ except Exception as exc : # noqa: BLE001 (자료·망 사정은 계약 위반이 아니다)
158+ skipped .append (f"{ providerName } : 인스턴스 생성 불가 ({ type (exc ).__name__ } : { exc } )" )
159+ return None
160+
161+
162+ def _closeCompany (company ) -> None :
163+ """탐침에 쓴 Company 를 닫는다. 정리 실패는 판정에 영향을 주지 않는다."""
164+ if hasattr (company , "__exit__" ):
165+ try :
166+ company .__exit__ (None , None , None )
167+ except Exception : # noqa: BLE001 (cleanup silent)
168+ pass
169+
170+
171+ def test_company_isinstance_runtime () -> None :
172+ """3 provider Company 인스턴스가 CompanyProtocol isinstance 를 만족한다.
173+
174+ 자료나 망 사정으로 인스턴스를 못 만든 provider 는 건너뛴다. 그것은 Protocol 적합성이
175+ 아니라 환경 문제이고, 그 실패 문구를 baseline 과 대조하면 게이트가 무작위로 빨간불이
176+ 된다. 생성자 계약이 어긋난 것만 위반으로 적는다.
123177 """
124178 from dartlab .core .protocols import CompanyProtocol
125179
126180 violations : list [str ] = []
181+ skipped : list [str ] = []
182+ checked = 0
127183 for providerName , stockCode in _providerProbes ():
128- try :
129- mod = importlib .import_module (f"dartlab.providers.{ providerName } .company" )
130- company = mod .Company (stockCode )
131- except Exception as exc : # noqa: BLE001 — 인스턴스 생성 실패 자체가 violation
132- violations .append (f"{ providerName } : 인스턴스 생성 실패 — { type (exc ).__name__ } : { exc } " )
184+ company = _openCompany (providerName , stockCode , violations , skipped )
185+ if company is None :
133186 continue
134-
135187 try :
188+ checked += 1
136189 if not isinstance (company , CompanyProtocol ):
137190 violations .append (f"{ providerName } : isinstance(co, CompanyProtocol) == False" )
138191 finally :
139- if hasattr (company , "__exit__" ):
140- try :
141- company .__exit__ (None , None , None )
142- except Exception : # noqa: BLE001 — cleanup silent
143- pass
192+ _closeCompany (company )
144193
145194 baseline = _loadBaseline ()
146195 allowed = set (baseline .get ("isinstanceRuntimeViolations" , []))
@@ -150,27 +199,36 @@ def test_company_isinstance_runtime() -> None:
150199 "P-PR0 baseline 에 등록하거나 Company 구현 보강 필요."
151200 )
152201
202+ baseline = _loadBaseline ()
203+ allowed = set (baseline .get ("isinstanceRuntimeViolations" , []))
204+ new_violations = set (violations ) - allowed
205+ assert not new_violations , (
206+ f"CompanyProtocol isinstance runtime 회귀 { len (new_violations )} 건: { new_violations } . "
207+ f"건너뛴 provider: { skipped } "
208+ )
209+ if checked == 0 :
210+ import pytest as _pytest
153211
154- def test_provider_namespaces_isinstance () -> None :
155- """co.docs / co.finance namespace 가 각 Provider Protocol 만족 (baseline 모드).
212+ _pytest .skip (f"어느 provider 도 인스턴스를 못 만들었다: { skipped } " )
156213
157- DocsProvider · FinanceProvider 의 메서드 시그니처 (fetchFiling/fetchStatements/...) 가
158- 3 provider namespace 에 매핑되는지 검증.
159214
160- namespace 부재 또는 isinstance 미통과 = violation. P-PR8 strict 전환.
215+ def test_provider_namespaces_isinstance () -> None :
216+ """co.docs 와 co.finance namespace 가 각 Provider Protocol 을 만족한다.
217+
218+ `test_company_isinstance_runtime` 과 같은 이유로, 자료나 망 사정으로 인스턴스를 못
219+ 만든 provider 는 건너뛴다. 위반 key 에 예외 메시지를 끼워 넣지 않는다.
161220 """
162221 from dartlab .core .protocols import DocsProvider , FinanceProvider
163222
164223 violations : list [str ] = []
224+ skipped : list [str ] = []
225+ checked = 0
165226 for providerName , stockCode in _providerProbes ():
166- try :
167- mod = importlib .import_module (f"dartlab.providers.{ providerName } .company" )
168- company = mod .Company (stockCode )
169- except Exception as exc : # noqa: BLE001
170- violations .append (f"{ providerName } : 인스턴스 생성 실패 — { type (exc ).__name__ } : { exc } " )
227+ company = _openCompany (providerName , stockCode , violations , skipped )
228+ if company is None :
171229 continue
172-
173230 try :
231+ checked += 1
174232 for nsName , protocolCls in (("docs" , DocsProvider ), ("finance" , FinanceProvider )):
175233 namespace = getattr (company , nsName , None )
176234 if namespace is None :
@@ -179,23 +237,52 @@ def test_provider_namespaces_isinstance() -> None:
179237 if not isinstance (namespace , protocolCls ):
180238 violations .append (f"{ providerName } .{ nsName } : isinstance({ protocolCls .__name__ } ) == False" )
181239 finally :
182- if hasattr (company , "__exit__" ):
183- try :
184- company .__exit__ (None , None , None )
185- except Exception : # noqa: BLE001
186- pass
240+ _closeCompany (company )
187241
188242 baseline = _loadBaseline ()
189243 allowed = set (baseline .get ("namespaceIsinstanceViolations" , []))
190244 new_violations = set (violations ) - allowed
191245 assert not new_violations , (
192- f"Namespace Protocol isinstance 회귀 { len (new_violations )} 건: { new_violations } . "
193- "P-PR0 baseline 에 등록하거나 namespace 구현 보강 필요."
246+ f"Namespace Protocol isinstance 회귀 { len (new_violations )} 건: { new_violations } . 건너뛴 provider: { skipped } "
194247 )
248+ if checked == 0 :
249+ import pytest as _pytest
250+
251+ _pytest .skip (f"어느 provider 도 인스턴스를 못 만들었다: { skipped } " )
195252
196253
197254def test_edinet_is_deferred_by_default () -> None :
198255 """EDINET 은 API 통신 불가 provider 이므로 기본 strict scope 에 포함하지 않는다."""
199256 if "edinet" in _providerScope ():
200- pytest .skip ("edinet 명시 scope — deferred 확인 생략" )
257+ pytest .skip ("edinet 명시 scope. deferred 확인 생략" )
201258 assert _DEFERRED_PROVIDERS == {"edinet" }
259+
260+
261+ def testViolationKeysCarryNoExceptionText () -> None :
262+ """위반 key 에 예외 메시지를 끼워 넣으면 차단 게이트가 무작위로 빨간불이 된다.
263+
264+ baseline 대조는 문자열 집합 비교다. key 에 `f"{type(exc).__name__}: {exc}"` 가 들어가면
265+ 망 사정, 시간 초과, 속도 제한이 매번 다른 문장을 내므로 같은 코드가 실행마다 다른 판정을
266+ 받는다. 실제로 CI 에서 이 게이트가 그렇게 빨간불이 났고 같은 커밋 재실행은 초록이었다.
267+
268+ 여기서 고정하는 것은 "위반 key 를 만드는 자리에 예외 값이 안 들어간다" 는 성질이다.
269+ 사람이 읽을 상세는 assert 문구와 skipped 목록으로 따로 나간다.
270+ """
271+ import ast as _ast
272+
273+ source = Path (__file__ ).read_text (encoding = "utf-8" )
274+ tree = _ast .parse (source )
275+ offenders : list [str ] = []
276+ for node in _ast .walk (tree ):
277+ if not isinstance (node , _ast .Call ):
278+ continue
279+ target = node .func
280+ if not isinstance (target , _ast .Attribute ) or target .attr != "append" :
281+ continue
282+ if not isinstance (target .value , _ast .Name ) or target .value .id != "violations" :
283+ continue
284+ rendered = _ast .unparse (node )
285+ if "exc" in {n .id for n in _ast .walk (node ) if isinstance (n , _ast .Name )}:
286+ offenders .append (rendered )
287+
288+ assert not offenders , f"위반 key 에 예외 값이 섞였다: { offenders } "
0 commit comments