白月黑羽教python之API接口自动化:课后练习

本博客记录了白月黑羽教python的API接口自动化课后作业的代码,方便以后查看,希望可以帮助看到这篇博客的人,最后感谢白月黑羽老师的免费教程,讲的非常清楚!

1、测试用例表

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2、代码文件布局

在这里插入图片描述

3、代码

#API/cases/空白/conftest.py
import pytest
from lib.webapi import apimgr

# 将环境初始化为为空白
@pytest.fixture(scope='package', autouse=True)
def st_emptyEnv():
    print(f'\n#### 初始化-删除客户、药品、订单')
    apimgr.mgr_login()
    apimgr.order_del_all()
    apimgr.customer_del_all()
    apimgr.medicine_del_all()

=================================================================================

#API/cases/空白/conftest.py/test_客户.py
import  pytest
from lib.webapi import apimgr


# 环境完全空白
class Test_0添删客户1_success:

    def setup_method(self):
        pass

    def teardown_method(self):
        # apimgr.customer_del(self.addedCustomerId)
        apimgr.customer_del_all()

    def test_API_0151(self):
        # '添加客户'
        r = apimgr.customer_add('武汉市桥西医院',
                                '13345679934',
                                "武汉市桥西医院北路")
        addRet = r.json()
        self.addedCustomerId = addRet['id']
        assert addRet['ret'] == 0
        # '检查系统数据'
        r = apimgr.customer_list()
        listRet = r.json()
        expected = {
            "ret": 0,
            "retlist": [
                {
                    "address": "武汉市桥西医院北路",
                    "id": addRet['id'],
                    "name": "武汉市桥西医院",
                    "phonenumber": "13345679934"
                }
            ],
            'total': 1
        }
        assert expected == listRet

    # 此用例不通过
    def test_API_0251(self):
        r = apimgr.customer_del(100000000000)
        editRet = r.json()#出错点:返回的响应r的消息体为html,无法应用json格式
        assert editRet== {
                            "ret": 1,
                            "msg":  "客户ID不存在",
                        }

        # 列出客户
        r = apimgr.customer_list()
        listRet = r.json()
        assert listRet['total'] == 0


class Test_0添改客户1_failure:

    #此用例不通过
    def test_API_0153(self):
        # '添加一个客户'
        r = apimgr.customer_add2({
                            "phonenumber":"13345679934",
                            "address":"南京市鼓楼北路"
                        })
        addRet = r.json()  #出错点:返回的响应r的消息体为html,无法应用json格式
        assert addRet == {
                        "ret": 1,
                        "msg":  "请求消息参数错误",
                    }
        # '检查系统数据'
        r = apimgr.customer_list()
        listRet = r.json()

        assert listRet == {
                    "ret": 0,
                    "retlist": [],
                    'total': 0
                }

    # 此用例不通过
    def test_API_0201(self):
        #修改不存在客户
        r=apimgr.customer_edit(10000000000,
                               {
                                "name":"武汉市桥北医院",
                                "phonenumber":"13345678888",
                                "address":"武汉市桥北医院北路"
                               })
        editRet = r.json()#出错点:返回的响应r的消息体为html,无法应用json格式
        assert editRet == {
            "ret": 1,
            "msg": "客户ID不存在",
        }
        #列出客户
        r = apimgr.customer_list()
        listRet = r.json()
        assert listRet['total']==0


class Test_10添加客户1_success:
    def setup_method(self):
        self.setup_data_customerids=[]
        for i in range(10):
            r = apimgr.customer_add(
                f'武汉市桥西医院_{i + 1}',
                f'100000000{i + 1:02d}',
                f"武汉市桥西医院北路_{i + 1}")
            self.setup_data_customerids.append(r.json()['id'])

    def teardown_method(self):
        for cid in self.setup_data_customerids:
            apimgr.customer_del(cid)
        apimgr.customer_del(self.addedCustomerId)


    def test_API_0152(self):
        #'先列出客户'
        r = apimgr.customer_list()
        listRet1 = r.json()
        customerlist1 = listRet1["retlist"]
        # '添加一个客户'
        r = apimgr.customer_add('南京市鼓楼医院',
                                '13345679934',
                                "南京市鼓楼北路")
        addRet = r.json()
        self.addedCustomerId = addRet['id']
        assert addRet['ret'] == 0
        # 再次列出客户'
        r = apimgr.customer_list(11)
        listRet = r.json()
        expected = {
            "ret": 0,
            "retlist": [
                           {
                               "address": "南京市鼓楼北路",
                               "id": addRet['id'],
                               "name": "南京市鼓楼医院",
                               "phonenumber": "13345679934"
                           }
                       ] + customerlist1,
            'total': 11
        }
        assert expected == listRet


class Test_1修改客户1_success:

    def setup_method(self):
        r = apimgr.customer_add('南京市鼓楼医院',
                                '13345679934',
                                "南京市鼓楼北路")
        addRet = r.json()
        self.addedCustomerId = addRet['id']

    def teardown_method(self):
        # apimgr.customer_del(self.addedCustomerId)
        apimgr.customer_del_all()

    def test_API_0202(self):
        r=apimgr.customer_edit(self.addedCustomerId,
                               {
                                "name":"武汉市桥北医院",
                               })
        editRet = r.json()
        assert editRet['ret'] ==0
        #列出客户
        r = apimgr.customer_list()
        listRet = r.json()
        expected = {
            "ret": 0,
            "retlist": [
                           {
                               "address": "南京市鼓楼北路",
                               "id": self.addedCustomerId,
                               "name": "武汉市桥北医院",
                               "phonenumber":'13345679934'
                           }
                       ],
            'total': 1
        }
        assert expected == listRet

    def test_API_0203(self):
        r = apimgr.customer_edit(self.addedCustomerId,
                                 {
                                     "phonenumber": "13886666666"
                                 })
        editRet = r.json()
        assert editRet['ret'] == 0
        # 列出客户
        r = apimgr.customer_list()
        listRet = r.json()
        expected = {
            "ret": 0,
            "retlist": [
                {
                    "address": "南京市鼓楼北路",
                    "id": self.addedCustomerId,
                    "name": '南京市鼓楼医院',
                    "phonenumber": "13886666666"
                }
            ],
            'total': 1
        }
        assert expected == listRet

    def test_API_0252(self):
        r = apimgr.customer_del(self.addedCustomerId)
        editRet = r.json()
        assert editRet['ret'] == 0
        # 列出客户
        r = apimgr.customer_list()
        listRet = r.json()
        assert listRet['total']==0



=================================================================================

#API/cfg/cfg.py
target_host = '127.0.0.1'

=================================================================================

#API/lib/webapi.py
import requests
from pprint import pprint
import pytest
import sys
sys.path.append("..")  #..代表上级目录,("../..")代表上级目录的上级目录
from cfg import cfg

class APIMgr:
     # 打印操作
    def _printResponse(self,response):
        print('\n\n-------- HTTP response * begin -------')
        print(response.status_code)

        for k,v in response.headers.items():
            print(f'{k}: {v}')

        print('')

        print(response.content.decode('utf8'))
        print('-------- HTTP response * end -------\n\n')

    # 登录操作
    def mgr_login(self,username='byhy',password='88888888',useProxy=False):
        self.s = requests.Session()

        if useProxy:
            self.s.proxies.update({'http': f'http://{cfg.target_host}:8888'})

        response = self.s.post(f"http://{cfg.target_host}/api/mgr/signin",
                                 data={
                                     'username': username,
                                     'password': password
                                 }
                                 )

        self._printResponse(response)
        return response


    # 客户操作
    def customer_list(self,pagesize=10,pagenumber=1,keywords=''):

        print('列出客户')
        response = self.s.get(f"http://{cfg.target_host}/api/mgr/customers",
              params={
                  'action' :'list_customer',
                  'pagesize' :pagesize,
                  'pagenum' :pagenumber,
                  'keywords' :keywords,
              })

        self._printResponse(response)
        return response


    def customer_add(self,name,phonenumber,address):
        print('添加客户')
        response = self.s.post(f"http://{cfg.target_host}/api/mgr/customers",
              json={
                    "action":"add_customer",
                    "data":{
                        "name":name,
                        "phonenumber":phonenumber,
                        "address":address
                    }
                })

        self._printResponse(response)
        return response

    def customer_add2(self,data):
        print('添加客户')
        response = self.s.post(f"http://{cfg.target_host}/api/mgr/customers",
              json={
                    "action":"add_customer",
                    "data":data
                })

        self._printResponse(response)
        return response

    def customer_del(self,cid):
        print('删除客户')
        response = self.s.delete(f"http://{cfg.target_host}/api/mgr/customers",
              json={
                    "action":"del_customer",
                    "id": cid
                })

        self._printResponse(response)
        return response

    def customer_del_all(self):
        response = self.customer_list(100,1)

        theList = response.json()["retlist"]
        for one in theList:
            self.customer_del(one["id"])

    def customer_edit(self,cid,data):
         print('修改客户')
         response=self.s.put(f"http://{cfg.target_host}/api/mgr/customers",
              json={
                    "action":"modify_customer",
                    "id": cid,
                    "newdata":data
                    }        )
         self._printResponse(response)
         return response

    # 药品操作

    def medicine_list(self,pagesize=10,pagenumber=1,keywords=''):
        print('列出药品')
        response = self.s.get(f"http://{cfg.target_host}/api/mgr/medicines",
              params={
                  'action' :'list_medicine',
                  'pagesize' :pagesize,
                  'pagenum' :pagenumber,
                  'keywords' :keywords,
              })

        self._printResponse(response)
        return response



    def medicine_del(self,mid):
        print('删除药品')
        response = self.s.delete(f"http://{cfg.target_host}/api/mgr/medicines",
              json={
                    "action":"del_medicine",
                    "id": mid
                })

        self._printResponse(response)
        return response


    def medicine_del_all(self):
        response = self.medicine_list(100,1)

        theList = response.json()["retlist"]
        for one in theList:
            self.medicine_del(one["id"])


    # 订单操作


    def order_list(self,pagesize=10,pagenumber=1,keywords=''):
        print('列出订单')
        response = self.s.get(f"http://{cfg.target_host}/api/mgr/orders",
              params={
                  'action' :'list_order',
                  'pagesize' :pagesize,
                  'pagenum' :pagenumber,
                  'keywords' :keywords,
              })

        self._printResponse(response)
        return response



    def order_del(self,oid):
        print('删除订单')
        response = self.s.delete(f"http://{cfg.target_host}/api/mgr/orders",
              json={
                    "action":"delete_order",
                    "id": oid
                })

        self._printResponse(response)
        return response


    def order_del_all(self):
        response = self.order_list(100,1)

        theList = response.json()["retlist"]
        for one in theList:
            self.order_del(one["id"])

apimgr = APIMgr()


=================================================================================

# 测试结果
============================================ short test summary info ============================================
FAILED cases/空白/test_客户.py::Test_0添删客户1_success::test_API_0251 - json.decoder.JSONDecodeError: Expectin...

FAILED cases/空白/test_客户.py::Test_0添改客户1_failure::test_API_0153 - json.decoder.JSONDecodeError: Expectin...

FAILED cases/空白/test_客户.py::Test_0添改客户1_failure::test_API_0201 - json.decoder.JSONDecodeError: Expectin...

========================================== 3 failed, 5 passed in 6.51s ==========================================

4、注意点

  1. Fiddler安装及使用

    Fiddler教程

    Fiddler Chrome配置和抓包

    抓包工具-fiddler出现“The system proxy was changed,click to reenable fiddler capture”的提示问题
    我的解决方法是:安装了进学校内网的easyconnect,卸载之后,就没有“The system proxy was changed,click to reenable fiddler capture”的提示问题了

    使用fiddler对手机上的程序进行抓包
    一步一步按教程来,手机先安装证书,再设置代理,前后顺序不要颠倒

  2. 模块调用方法

    python import 上级目录 及同级兄弟目录中的模块

  3. 类内函数调用类内另一个函数的变量

    (1)将该变量添加到self参考文章

    (2)使用全局变量 global参考文章

  4. 由pytest中类初始化和方法初始化区别引发的思考

    python中self和cls的区别

  5. python问题unindent does not match any outer indentation level在pycharm平台的解决方法

    这种情况一般是由于 缩进 参考文章

5、知识点总结

在这里插入图片描述

代码封装的简洁性不够,其次因为时间仓促,这一部分只做了最后一节的练习题,有点遗憾的感觉。

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
我很抱歉,我不了解“白月羽”提供的Python教程。然而,Python是一门广泛使用的编程语言,有许多资源可供学习。以下是一些常用的Python学习资源: 1. 官方文档:Python官方网站提供了详细的官方文档,其中包含了Python的语法、模块和标准库的说明。您可以访问官方网站(https://www.python.org)并查看相关文档。 2. 在线教程:有许多免费的在线Python教程可供选择。一些受欢迎的在线教育平台,如Coursera、Udemy和Codecademy,提供了Python编程课程。您可以在这些平台上搜索并选择适合您的课程。 3. 图书:有很多优秀的Python编程书籍可供学习。一些经典的Python入门书籍包括《Python编程快速上手——让繁琐工作自动化》、《Python编程从入门到实践》等。您可以通过在线书店或图书馆获取这些书籍。 4. 社区和论坛:加入Python开发者社区和论坛,与其他Python爱好者交流和学习。可以参加Python开发者大会,订阅Python相关的邮件列表或加入在线论坛如Stack Overflow来获取帮助和经验分享。 5. 实践项目:通过实际编写代码来提高您的Python编程能力。尝试解决一些小项目或参与开源项目,这将帮助您应用所学的知识并提升技能。 请记住,学习编程需要持续的练习和实践。从基础知识开始,逐渐深入学习,并通过编写代码来巩固所学的内容。祝您在学习Python的过程中取得成功!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值