test_common.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. """Unit tests for _common.py — pure logic only, no network."""
  2. from __future__ import annotations
  3. import pytest
  4. from _common import (
  5. EMBEDDING_REGEX,
  6. cloud_endpoint,
  7. coerce_seed,
  8. folder_aliases_for,
  9. is_api_format,
  10. is_cloud_host,
  11. is_link,
  12. iter_embedding_refs,
  13. iter_model_deps,
  14. iter_nodes,
  15. looks_like_video_workflow,
  16. media_type_from_filename,
  17. parse_model_list,
  18. resolve_url,
  19. safe_path_join,
  20. unwrap_workflow,
  21. )
  22. # =============================================================================
  23. # Cloud detection / URL routing
  24. # =============================================================================
  25. class TestCloudDetection:
  26. def test_cloud_host_exact(self):
  27. assert is_cloud_host("https://cloud.comfy.org") is True
  28. assert is_cloud_host("https://cloud.comfy.org/foo/bar") is True
  29. def test_cloud_host_subdomain(self):
  30. assert is_cloud_host("https://staging.cloud.comfy.org") is True
  31. assert is_cloud_host("https://api.cloud.comfy.org") is True
  32. def test_local_not_cloud(self):
  33. assert is_cloud_host("http://127.0.0.1:8188") is False
  34. assert is_cloud_host("http://localhost:8188") is False
  35. assert is_cloud_host("http://my-server.local:8188") is False
  36. def test_no_scheme(self):
  37. # Defaults to http://
  38. assert is_cloud_host("cloud.comfy.org") is True
  39. assert is_cloud_host("127.0.0.1:8188") is False
  40. class TestCloudEndpointRename:
  41. def test_history_renamed(self):
  42. assert cloud_endpoint("/history") == "/history_v2"
  43. assert cloud_endpoint("/history/abc-123") == "/history_v2/abc-123"
  44. def test_history_v2_preserved(self):
  45. assert cloud_endpoint("/history_v2") == "/history_v2"
  46. def test_models_renamed(self):
  47. assert cloud_endpoint("/models") == "/experiment/models"
  48. assert cloud_endpoint("/models/checkpoints") == "/experiment/models/checkpoints"
  49. assert cloud_endpoint("/models/loras") == "/experiment/models/loras"
  50. def test_other_paths_unchanged(self):
  51. assert cloud_endpoint("/prompt") == "/prompt"
  52. assert cloud_endpoint("/queue") == "/queue"
  53. class TestResolveURL:
  54. def test_local_no_prefix(self):
  55. assert resolve_url("http://127.0.0.1:8188", "/prompt") == "http://127.0.0.1:8188/prompt"
  56. def test_cloud_adds_api_prefix(self):
  57. assert resolve_url("https://cloud.comfy.org", "/prompt") == "https://cloud.comfy.org/api/prompt"
  58. def test_cloud_history_renamed(self):
  59. assert resolve_url("https://cloud.comfy.org", "/history/abc") == "https://cloud.comfy.org/api/history_v2/abc"
  60. def test_cloud_models_renamed(self):
  61. assert resolve_url("https://cloud.comfy.org", "/models/loras") == "https://cloud.comfy.org/api/experiment/models/loras"
  62. def test_cloud_already_has_api(self):
  63. # Don't double-prefix
  64. assert resolve_url("https://cloud.comfy.org", "/api/prompt") == "https://cloud.comfy.org/api/prompt"
  65. def test_trailing_slash_stripped(self):
  66. assert resolve_url("http://127.0.0.1:8188/", "/prompt") == "http://127.0.0.1:8188/prompt"
  67. # =============================================================================
  68. # Workflow validation
  69. # =============================================================================
  70. class TestAPIFormatDetection:
  71. def test_valid_api(self, sd15_workflow):
  72. assert is_api_format(sd15_workflow) is True
  73. def test_editor_format_rejected(self):
  74. editor = {"nodes": [], "links": [], "version": 0.4}
  75. assert is_api_format(editor) is False
  76. def test_empty_dict(self):
  77. assert is_api_format({}) is False
  78. def test_non_dict(self):
  79. assert is_api_format([]) is False
  80. assert is_api_format(None) is False
  81. assert is_api_format("string") is False
  82. def test_node_with_class_type(self):
  83. wf = {"3": {"class_type": "KSampler", "inputs": {}}}
  84. assert is_api_format(wf) is True
  85. class TestUnwrapWorkflow:
  86. def test_passthrough_api_format(self, sd15_workflow):
  87. result = unwrap_workflow(sd15_workflow)
  88. assert result is sd15_workflow
  89. def test_unwrap_prompt_key(self, sd15_workflow):
  90. wrapped = {"prompt": sd15_workflow, "client_id": "abc"}
  91. result = unwrap_workflow(wrapped)
  92. assert result is sd15_workflow
  93. def test_editor_format_raises(self):
  94. with pytest.raises(ValueError, match="editor format"):
  95. unwrap_workflow({"nodes": [], "links": []})
  96. def test_garbage_raises(self):
  97. with pytest.raises(ValueError):
  98. unwrap_workflow({"foo": "bar"})
  99. class TestIsLink:
  100. def test_valid_link(self):
  101. assert is_link(["3", 0]) is True
  102. assert is_link(["10", 1]) is True
  103. def test_non_link(self):
  104. assert is_link("string") is False
  105. assert is_link(42) is False
  106. assert is_link([]) is False
  107. assert is_link(["3"]) is False # missing slot
  108. assert is_link(["3", "0"]) is False # slot must be int
  109. assert is_link([3, 0]) is False # node_id must be string
  110. # =============================================================================
  111. # Workflow iterators
  112. # =============================================================================
  113. class TestIterators:
  114. def test_iter_nodes(self, sd15_workflow):
  115. nodes = dict(iter_nodes(sd15_workflow))
  116. assert "3" in nodes
  117. assert nodes["3"]["class_type"] == "KSampler"
  118. def test_iter_nodes_skips_comments(self, sd15_workflow):
  119. # _comment is not a node
  120. nodes = dict(iter_nodes(sd15_workflow))
  121. assert "_comment" not in nodes
  122. def test_iter_model_deps(self, sd15_workflow):
  123. deps = list(iter_model_deps(sd15_workflow))
  124. names = [d["value"] for d in deps]
  125. assert "v1-5-pruned-emaonly.safetensors" in names
  126. def test_iter_model_deps_flux(self, flux_workflow):
  127. deps = list(iter_model_deps(flux_workflow))
  128. names = {d["value"]: d["folder"] for d in deps}
  129. assert names["flux1-dev.safetensors"] == "unet"
  130. assert names["t5xxl_fp16.safetensors"] == "clip"
  131. assert names["clip_l.safetensors"] == "clip"
  132. assert names["ae.safetensors"] == "vae"
  133. # =============================================================================
  134. # Embedding extraction
  135. # =============================================================================
  136. class TestEmbeddingRegex:
  137. def test_basic_embedding(self):
  138. m = EMBEDDING_REGEX.search("a cat, embedding:goodvibes, more text")
  139. assert m is not None
  140. assert m.group(1) == "goodvibes"
  141. def test_embedding_with_strength(self):
  142. m = EMBEDDING_REGEX.search("embedding:bad-hands-5:1.2")
  143. assert m is not None
  144. assert m.group(1) == "bad-hands-5"
  145. def test_embedding_with_extension(self):
  146. # Strips .pt / .safetensors / .bin
  147. m = EMBEDDING_REGEX.search("embedding:my-emb.pt")
  148. assert m is not None
  149. assert m.group(1) == "my-emb"
  150. def test_embedding_in_parens(self):
  151. m = EMBEDDING_REGEX.search("(embedding:foo:0.8)")
  152. assert m is not None
  153. assert m.group(1) == "foo"
  154. def test_multiple_in_one_string(self):
  155. text = "a cat, embedding:foo:1.2, and embedding:bar"
  156. matches = [m.group(1) for m in EMBEDDING_REGEX.finditer(text)]
  157. assert matches == ["foo", "bar"]
  158. def test_no_false_positive_on_word_embedding(self):
  159. # "embedding " (with space, no colon) should not match
  160. m = EMBEDDING_REGEX.search("the embedding is great")
  161. assert m is None
  162. class TestIterEmbeddingRefs:
  163. def test_finds_in_clip_text_encode(self):
  164. wf = {
  165. "1": {"class_type": "CLIPTextEncode",
  166. "inputs": {"text": "embedding:foo, embedding:bar:0.5", "clip": ["2", 0]}},
  167. "2": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "x"}},
  168. }
  169. refs = list(iter_embedding_refs(wf))
  170. names = [name for _, name in refs]
  171. assert names == ["foo", "bar"]
  172. def test_ignores_non_prompt_fields(self):
  173. wf = {
  174. "1": {"class_type": "CheckpointLoaderSimple",
  175. "inputs": {"ckpt_name": "embedding:foo.safetensors"}},
  176. }
  177. refs = list(iter_embedding_refs(wf))
  178. # ckpt_name is not a prompt field — ignored
  179. assert refs == []
  180. # =============================================================================
  181. # Path safety
  182. # =============================================================================
  183. class TestSafePathJoin:
  184. def test_normal_join(self, tmp_path):
  185. p = safe_path_join(tmp_path, "subdir", "file.png")
  186. assert p.is_relative_to(tmp_path)
  187. def test_blocks_traversal(self, tmp_path):
  188. with pytest.raises(ValueError, match="path traversal"):
  189. safe_path_join(tmp_path, "..", "..", "etc", "passwd")
  190. def test_blocks_absolute(self, tmp_path):
  191. with pytest.raises(ValueError):
  192. safe_path_join(tmp_path, "/etc/passwd")
  193. def test_subfolder_with_filename(self, tmp_path):
  194. p = safe_path_join(tmp_path, "outputs", "img.png")
  195. assert p.name == "img.png"
  196. assert p.parent.name == "outputs"
  197. # =============================================================================
  198. # Seed coercion
  199. # =============================================================================
  200. class TestCoerceSeed:
  201. def test_explicit_int(self):
  202. assert coerce_seed(42) == 42
  203. assert coerce_seed(0) == 0
  204. def test_minus_one_randomizes(self):
  205. s = coerce_seed(-1)
  206. assert isinstance(s, int)
  207. assert 0 <= s < 2**63
  208. def test_none_randomizes(self):
  209. s = coerce_seed(None)
  210. assert isinstance(s, int)
  211. def test_string_int(self):
  212. # str() that converts cleanly is allowed (relaxed)
  213. assert coerce_seed("12345") == 12345
  214. def test_string_minus_one_randomizes(self):
  215. # CLI / JSON sometimes carries seed as a string.
  216. s = coerce_seed("-1")
  217. assert isinstance(s, int)
  218. assert 0 <= s < 2**63
  219. # And whitespace tolerated
  220. s2 = coerce_seed(" -1 ")
  221. assert isinstance(s2, int)
  222. assert 0 <= s2 < 2**63
  223. # =============================================================================
  224. # Model list normalization (cloud format)
  225. # =============================================================================
  226. class TestParseModelList:
  227. def test_local_format_strings(self):
  228. result = parse_model_list(["a.safetensors", "b.safetensors"])
  229. assert result == {"a.safetensors", "b.safetensors"}
  230. def test_cloud_format_dicts(self):
  231. result = parse_model_list([
  232. {"name": "a.safetensors", "pathIndex": 0},
  233. {"name": "b.safetensors", "pathIndex": 1},
  234. ])
  235. assert result == {"a.safetensors", "b.safetensors"}
  236. def test_empty(self):
  237. assert parse_model_list([]) == set()
  238. def test_garbage(self):
  239. assert parse_model_list("not a list") == set()
  240. assert parse_model_list(None) == set()
  241. def test_mixed_format(self):
  242. result = parse_model_list([
  243. "string-form.safetensors",
  244. {"name": "dict-form.safetensors"},
  245. ])
  246. assert result == {"string-form.safetensors", "dict-form.safetensors"}
  247. # =============================================================================
  248. # Folder aliases
  249. # =============================================================================
  250. class TestFolderAliases:
  251. def test_unet_aliases_diffusion_models(self):
  252. aliases = folder_aliases_for("unet")
  253. assert "unet" in aliases
  254. assert "diffusion_models" in aliases
  255. def test_clip_aliases_text_encoders(self):
  256. aliases = folder_aliases_for("clip")
  257. assert "clip" in aliases
  258. assert "text_encoders" in aliases
  259. def test_unknown_folder_returns_self(self):
  260. assert folder_aliases_for("checkpoints") == ["checkpoints"]
  261. def test_primary_first(self):
  262. # Order matters: primary should be first for human-friendly fix hints
  263. assert folder_aliases_for("unet")[0] == "unet"
  264. assert folder_aliases_for("diffusion_models")[0] == "diffusion_models"
  265. # =============================================================================
  266. # Media-type detection
  267. # =============================================================================
  268. class TestMediaType:
  269. def test_video_extensions(self):
  270. assert media_type_from_filename("vid.mp4") == "video"
  271. assert media_type_from_filename("foo.webm") == "video"
  272. assert media_type_from_filename("bar.gif") == "video"
  273. def test_audio_extensions(self):
  274. assert media_type_from_filename("song.wav") == "audio"
  275. assert media_type_from_filename("music.mp3") == "audio"
  276. def test_image_default(self):
  277. assert media_type_from_filename("pic.png") == "image"
  278. assert media_type_from_filename("image.jpg") == "image"
  279. assert media_type_from_filename("unknown.xyz") == "image"
  280. def test_3d(self):
  281. assert media_type_from_filename("model.glb") == "3d"
  282. assert media_type_from_filename("scene.gltf") == "3d"
  283. # =============================================================================
  284. # Cross-host header stripping (security)
  285. # =============================================================================
  286. class TestRedirectHeaderStripping:
  287. """Verify X-API-Key is dropped when redirect crosses to a different host
  288. (e.g. cloud /api/view → S3 signed URL). Critical to prevent leaking auth
  289. tokens to the storage backend.
  290. """
  291. def _build_session(self):
  292. from _common import _StripSensitiveOnRedirectSession, HAS_REQUESTS
  293. if not HAS_REQUESTS:
  294. import pytest
  295. pytest.skip("requests not installed")
  296. return _StripSensitiveOnRedirectSession()
  297. def test_strips_x_api_key_cross_host(self):
  298. import requests
  299. s = self._build_session()
  300. prep = requests.PreparedRequest()
  301. prep.prepare(method="GET", url="https://other.example.com/file",
  302. headers={"X-API-Key": "leak", "Authorization": "Bearer x"})
  303. resp = requests.Response()
  304. orig = requests.PreparedRequest()
  305. orig.prepare(method="GET", url="https://cloud.comfy.org/api/view", headers={})
  306. resp.request = orig
  307. s.rebuild_auth(prep, resp)
  308. assert "X-API-Key" not in prep.headers
  309. assert "Authorization" not in prep.headers
  310. def test_preserves_x_api_key_same_host(self):
  311. import requests
  312. s = self._build_session()
  313. prep = requests.PreparedRequest()
  314. prep.prepare(method="GET", url="https://cloud.comfy.org/foo",
  315. headers={"X-API-Key": "keep"})
  316. resp = requests.Response()
  317. orig = requests.PreparedRequest()
  318. orig.prepare(method="GET", url="https://cloud.comfy.org/bar", headers={})
  319. resp.request = orig
  320. s.rebuild_auth(prep, resp)
  321. assert prep.headers.get("X-API-Key") == "keep"
  322. def test_strips_cookie_cross_host(self):
  323. import requests
  324. s = self._build_session()
  325. prep = requests.PreparedRequest()
  326. prep.prepare(method="GET", url="https://other.example.com/x",
  327. headers={"Cookie": "session=secret"})
  328. resp = requests.Response()
  329. orig = requests.PreparedRequest()
  330. orig.prepare(method="GET", url="https://cloud.comfy.org/foo", headers={})
  331. resp.request = orig
  332. s.rebuild_auth(prep, resp)
  333. assert "Cookie" not in prep.headers
  334. # =============================================================================
  335. # Video workflow detection
  336. # =============================================================================
  337. class TestVideoWorkflow:
  338. def test_image_workflow(self, sd15_workflow):
  339. assert looks_like_video_workflow(sd15_workflow) is False
  340. def test_animatediff_workflow(self, workflows_dir):
  341. import json
  342. wf = json.loads((workflows_dir / "animatediff_video.json").read_text(encoding="utf-8"))
  343. assert looks_like_video_workflow(wf) is True
  344. def test_wan_workflow(self, video_workflow):
  345. assert looks_like_video_workflow(video_workflow) is True