惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
O
OpenAI News
S
Schneier on Security
Latest news
Latest news
Security Latest
Security Latest
NISL@THU
NISL@THU
V
Vulnerabilities – Threatpost
酷 壳 – CoolShell
酷 壳 – CoolShell
I
Intezer
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
博客园 - Franky
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 叶小钗
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Apple Machine Learning Research
Apple Machine Learning Research
V
Visual Studio Blog
爱范儿
爱范儿
小众软件
小众软件
腾讯CDC
T
The Exploit Database - CXSecurity.com
美团技术团队
博客园 - 司徒正美
A
Arctic Wolf
人人都是产品经理
人人都是产品经理
博客园 - 【当耐特】
The Hacker News
The Hacker News
T
Tenable Blog
J
Java Code Geeks
V
V2EX
博客园 - 三生石上(FineUI控件)
罗磊的独立博客
K
Kaspersky official blog
IT之家
IT之家
P
Palo Alto Networks Blog
L
LINUX DO - 热门话题
博客园 - 聂微东
Cloudbric
Cloudbric
PCI Perspectives
PCI Perspectives
C
Cyber Attacks, Cyber Crime and Cyber Security
量子位
Forbes - Security
Forbes - Security
V2EX - 技术
V2EX - 技术
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Cloudflare Blog

pytest

pytest 求几个项目练手 - V2EX pytest 安装到虚拟环境 - V2EX Python 蛋疼的单元测试 - V2EX 关于Python单元测试框架 - V2EX
请教个 py.test 的使用问题( case 间参数依赖) - V2EX
iyaozhen · 2016-12-24 · via pytest

大概的代码是这样:

import requests
import pytest

class TestRestApi():
    url = 'http://xxx.com'

    @pytest.fixture(scope="session")
    def http_session(self):
        # 省略设置 cookie 等步骤,返回一个 request.session 对象
        return requests.Session()

    def test_api_a(self, http_session):
        response = http_session.post(self.url + '/app/sessioncontextget', json=body)
        assert response.status_code == 200
        data = response.json()
        # 我想保存此 api 的一个返回值
        self.session_id = data['data']['session_id']
        assert data['code'] == 200

    def test_api_b(self, http_session):
        body = {
            # 请求参数依赖前一个 api 的返回值
            "sessionid": self.session_id,
        }
        response = http_session.post(self.url_ge + '/api/taskcreate', json=body)
        assert response.status_code == 200
        data = response.json()
        assert data['errcode'] == 0

断点调试发现 session_id 是设置成功了的, test_api_a 也测试通过

但运行到 test_api_b 时却提示:AttributeError: 'TestRestApi' object has no attribute 'session_id'。不过这也很好理解,单测本来就是每个 case 独立的,每次相当于都是重新运行。

那么问题来了,这个需求怎么解决?

还有一个问题, pytest.fixture 的特性感觉不是很方便, http_session 变量无法被 IDE 识别,没有代码提示了(不过这个影响很小),关键是每个测试 case 都要传入 http_session 参数,感觉不够简洁。

初次使用 py.test ,可能理解不是很透彻,还请见谅。