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

推荐订阅源

Engineering at Meta
Engineering at Meta
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Visual Studio Blog
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
腾讯CDC
S
Securelist
Know Your Adversary
Know Your Adversary
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - 【当耐特】
V2EX - 技术
V2EX - 技术
J
Java Code Geeks
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Hugging Face - Blog
Hugging Face - Blog
Cisco Talos Blog
Cisco Talos Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
W
WeLiveSecurity
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
博客园 - Franky
S
Security Affairs
博客园 - 司徒正美
V
V2EX
K
Kaspersky official blog
T
Threatpost
NISL@THU
NISL@THU
博客园 - 叶小钗
Help Net Security
Help Net Security
PCI Perspectives
PCI Perspectives
IT之家
IT之家
小众软件
小众软件
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Last Week in AI
Last Week in AI
Jina AI
Jina AI
爱范儿
爱范儿
罗磊的独立博客
N
News and Events Feed by Topic
博客园 - 三生石上(FineUI控件)
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
L
LINUX DO - 热门话题
Google Online Security Blog
Google Online Security Blog
雷峰网
雷峰网
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint

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 ,可能理解不是很透彻,还请见谅。