蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 Redis 8 连接鉴权、PING/ECHO、逻辑库切换与 QUIT 实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-connection.py
explore-connection.py124 行
"""Offline Redis 8 lab for Ch 17 (connection): AUTH, PING, ECHO, SELECT, QUIT."""
import json
import subprocess

VERSION = "CPython 3.12.14 / offline Docker redis:8-alpine (--network none)"


def run_in_redis(shell_script: str) -> str:
    proc = subprocess.run(
        ["docker", "run", "--rm", "--network", "none", "redis:8-alpine", "sh", "-c", shell_script],
        capture_output=True,
        encoding="utf-8",
        check=True,
        timeout=60,
    )
    return proc.stdout


def main():
    script = r"""
set -e
redis-server --daemonize yes --save '' --appendonly no --dir /tmp --requirepass "demo-pass-17"
until redis-cli -a "demo-pass-17" --no-auth-warning PING >/dev/null 2>&1; do sleep 0.05; done

echo "===CASE1_NOAUTH==="
redis-cli --raw PING 2>&1 || true
echo "===CASE1_AUTH==="
printf 'AUTH "demo-pass-17"\r\nPING\r\nPING "hello"\r\nQUIT\r\n' | nc 127.0.0.1 6379

echo "===CASE2==="
redis-cli -a "demo-pass-17" --no-auth-warning --raw ECHO "Redis Connection OK"

echo "===CASE3==="
printf 'AUTH "demo-pass-17"\r\nSELECT 0\r\nSET slot_key db0_val\r\nSELECT 1\r\nGET slot_key\r\nSET slot_key db1_val\r\nSELECT 0\r\nGET slot_key\r\nSELECT 1\r\nGET slot_key\r\nQUIT\r\n' | nc 127.0.0.1 6379

echo "===CASE4==="
printf 'AUTH "demo-pass-17"\r\nPING\r\nQUIT\r\n' | nc 127.0.0.1 6379
"""
    raw = run_in_redis(script).replace("\r\n", "\n")
    sections = {}
    cur = None
    for line in raw.splitlines():
        if line.startswith("===") and line.endswith("==="):
            cur = line.strip("=")
            sections[cur] = []
        elif cur is not None:
            sections[cur].append(line)

    noauth_msg = " ".join(sections["CASE1_NOAUTH"])
    c1_lines = sections["CASE1_AUTH"]
    c1_actual = {
        "noauth_rejected": "NOAUTH" in noauth_msg,
        "auth_ok": "+OK" in c1_lines,
        "ping_pong": "+PONG" in c1_lines,
        "ping_message": "hello" in c1_lines,
    }
    c1_expected = {
        "noauth_rejected": True,
        "auth_ok": True,
        "ping_pong": True,
        "ping_message": True,
    }

    c2_actual = sections["CASE2"][0] if sections["CASE2"] else ""
    c2_expected = "Redis Connection OK"

    c3_lines = sections["CASE3"]
    c3_actual = {
        "db1_initially_nil": "$-1" in c3_lines,
        "db0_val": "db0_val" in c3_lines,
        "db1_val": "db1_val" in c3_lines,
    }
    c3_expected = {
        "db1_initially_nil": True,
        "db0_val": True,
        "db1_val": True,
    }

    c4_lines = sections["CASE4"]
    c4_actual = {
        "ping_ok": "+PONG" in c4_lines,
        "quit_ok": c4_lines.count("+OK") == 2,  # AUTH + QUIT
    }
    c4_expected = {
        "ping_ok": True,
        "quit_ok": True,
    }

    cases = [
        dict(
            name="auth_and_ping_roundtrip",
            summary="未认证触发 NOAUTH,AUTH 验证密码后 PING 返回 PONG 与回显消息",
            expected=c1_expected,
            actual=c1_actual,
            passed=(c1_actual == c1_expected),
        ),
        dict(
            name="echo_string_roundtrip",
            summary="ECHO 命令原样回传测试字符串",
            expected=c2_expected,
            actual=c2_actual,
            passed=(c2_actual == c2_expected),
        ),
        dict(
            name="select_db_isolation",
            summary="SELECT 切换 0 号与 1 号逻辑数据库,验证同名键相互隔离",
            expected=c3_expected,
            actual=c3_actual,
            passed=(c3_actual == c3_expected),
        ),
        dict(
            name="quit_closes_session",
            summary="QUIT 命令正常返回 OK 并关闭当前客户端会话",
            expected=c4_expected,
            actual=c4_actual,
            passed=(c4_actual == c4_expected),
        ),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/redis-connection-lab/explore-connection.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-connection.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Redis

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1784.zip

下载课程关联工程包:Redis

课程关联工程包(登记关联28章) · 含当前章节或实例 · mbskycom202612a1778.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习