79 lines
2.6 KiB
Python
79 lines
2.6 KiB
Python
# rpa_oracle.env:.env 只补缺,不覆盖已有非空环境变量。
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
|
||
from rpa_oracle.env import job_env_files, load_env
|
||
|
||
|
||
# 缺的键从文件补上,已有非空环境变量保持不变。
|
||
def test_load_env_fills_missing_and_keeps_existing(tmp_path, monkeypatch):
|
||
monkeypatch.setenv("OMS_REPO", "memory")
|
||
monkeypatch.delenv("RPA_ORACLE_PASSWORD", raising=False)
|
||
env_file = tmp_path / ".env"
|
||
env_file.write_text(
|
||
"OMS_REPO=oracle\nRPA_ORACLE_PASSWORD=not-for-git\n# comment\n\n",
|
||
encoding="utf-8",
|
||
)
|
||
load_env(env_file)
|
||
assert os.environ["OMS_REPO"] == "memory"
|
||
assert os.environ["RPA_ORACLE_PASSWORD"] == "not-for-git"
|
||
|
||
|
||
# 已有变量为空字符串时,用 .env 里的值补上。
|
||
def test_load_env_fills_empty_existing(tmp_path, monkeypatch):
|
||
monkeypatch.setenv("RPA_ORACLE_USER", "")
|
||
env_file = tmp_path / ".env"
|
||
env_file.write_text("RPA_ORACLE_USER=rpainit\n", encoding="utf-8")
|
||
load_env(env_file)
|
||
assert os.environ["RPA_ORACLE_USER"] == "rpainit"
|
||
|
||
|
||
# 去掉值两边成对的单引号或双引号。
|
||
def test_load_env_strips_matching_quotes(tmp_path, monkeypatch):
|
||
monkeypatch.delenv("FOO", raising=False)
|
||
monkeypatch.delenv("BAZ", raising=False)
|
||
env_file = tmp_path / ".env"
|
||
env_file.write_text("FOO=\"bar\"\nBAZ='qux'\n", encoding="utf-8")
|
||
load_env(env_file)
|
||
assert os.environ["FOO"] == "bar"
|
||
assert os.environ["BAZ"] == "qux"
|
||
|
||
|
||
# 加购先读本包,再读选品,最后读 oms。
|
||
def test_job_env_files_cart_includes_selection_then_oms(tmp_path):
|
||
cart = tmp_path / "rpa_cart"
|
||
cart.mkdir()
|
||
assert job_env_files(cart) == (
|
||
cart / ".env",
|
||
tmp_path / "rpa_selection" / ".env",
|
||
tmp_path / "rpa_oms" / ".env",
|
||
)
|
||
|
||
|
||
# 选品、合同、返利不读商城 .env,只补 oms。
|
||
def test_job_env_files_other_package_skips_selection(tmp_path):
|
||
selection = tmp_path / "rpa_selection"
|
||
selection.mkdir()
|
||
assert job_env_files(selection) == (
|
||
selection / ".env",
|
||
tmp_path / "rpa_oms" / ".env",
|
||
)
|
||
|
||
|
||
# 文件不存在时不报错、不改环境。
|
||
def test_load_env_missing_file_is_noop(tmp_path):
|
||
load_env(tmp_path / "nope.env")
|
||
|
||
|
||
# 多个 .env 按顺序补缺,先读到的非空值留下。
|
||
def test_load_env_later_file_does_not_override_earlier(tmp_path, monkeypatch):
|
||
monkeypatch.delenv("A", raising=False)
|
||
one = tmp_path / "a.env"
|
||
two = tmp_path / "b.env"
|
||
one.write_text("A=first\n", encoding="utf-8")
|
||
two.write_text("A=second\n", encoding="utf-8")
|
||
load_env(one, two)
|
||
assert os.environ["A"] == "first"
|