接口测试实战1

Roy_Fielding:https://en.wikipedia.org/wiki/Roy_Fielding
论文:https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

企业微信 api 文档:接口文档 - 企业微信开发者中心

image

python
pytest
requests: https://requests.readthedocs.io/zh_CN/latest/user/quickstart.html

作业

  1. 使用 requests 实现部门的增删改查
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import requests


class TestDepartment:
    secrete = 'rjLxujzktWgM6gTAWOVYP24m18QBOF3NqNr-tEm78Uw'
    id = 'ww5c26515c581b70fd'

    def setup(self):
        r = requests.get(f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.id}&corpsecret={self.secrete}')
        self.token = r.json()['access_token']

    def test_department(self):
        createDate = {
            "name": "CD研发中心",
            "name_en": "RDGZ",
            "parentid": 1,
            "order": 1,
            "id": 2
        }
        # 创建部门
        create_department = requests.post(f'https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token='+self.token, json=createDate)
        if create_department.json()['errcode'] == 0:
            # 获取部门
            get_department = requests.get(f'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='+self.token+'&id=1')
            print(get_department.json())
            assert get_department.json()['errcode'] == 0

        # 更新部门
        updateDate = {
            "id": 2,
            "name": "CD研发中心RICE",
            "name_en": "RDGZ1"
        }
        update_department = requests.post(f'https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token='+self.token, json=updateDate)
        print(update_department.json())

        # 删除部门
        delete_department = requests.get(f'https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token='+self.token+'&id=2')
        print(delete_department.json())
        assert delete_department.json()['errcode'] == 0

测试结果:

import requests
import json
class Testdemo:
    corpid = 'xxx'
    corpsecret = 'xxx'
    def setup(self):
        r=requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.corpid}&corpsecret={self.corpsecret}")
        print(r.json())
        self.token=r.json()["access_token"]


    def testone(self):
        r = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.token}&id=2")
        if r.json()["errcode"] != 0:
            create_json = {
                "name": "广州研发中心",
                "name_en": "RDGZ",
                "parentid": 1,
                "order": 1,
                "id": 2
            }
            a=json.dumps(create_json,ensure_ascii=False)
            # dumps-> 将字典转为字符串
            b=json.loads(a)
            # loads-> 将字符串转为列表
            #对应dump 和load 指结合文件操作
            r = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.token}",
                              json=b)
            print(r.json())
            update_json = {
                "id": 2,
                "name": "广州研发中心修改",
                "name_en": "RDGZ",
                "parentid": 1,
                "order": 1
            }
            r = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={self.token}",
                              json=update_json)
            print(r.json())
        else:
            r = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={self.token}&id=2")
            print(r.json())

使用requesets对企业微信的部门进行增删改查操作,直接操作在Test_department类中,yaml进行数据驱动在Test_Department_withyaml类中

https://github.com/q838732947/devtest/blob/master/http/workweixin/test_department.py

https://github.com/mengqiD11/Http/blob/master/test_wework.py

import json
import pytest
import requests


class TestDepartment:
    ID = 'wwb1ddeb81fc3c9d4b'
    SECRETE = 'BlNz4PGgNN_mZ81AixmbAj-eYnPek2jGa9Hs4bOqtqw'

    def setup(self):
        r = requests.get(f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.ID}&corpsecret={self.SECRETE}')
        self.access_token = r.json()['access_token']
        print(r.json()['access_token'])

    @pytest.mark.parametrize('name, parentid',
                             [('技术中心', 1), ('财务中心', 2)])
    def test_create_department(self, name, parentid):
        url = f'https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.access_token}'
        data = {
            'name': name,
            'parentid': parentid
        }

        r = requests.post(url=url, data=json.dumps(data))
        assert r.json()['errcode'] == 0

    def test_get_department(self, userid=None):
        url = r'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.access_token}}'
        if userid is not None:
            url = url + f'userid={userid}'
        r = requests.get(url=url)
        print(r.json())
        assert r.json()['errcode'] == 0

    @pytest.mark.parametrize("id, name, name_en",
                             [(1, "技术中心", None), (2, "财务中心", "caiwu")])
    def test_update_department(self, id, name, name_en):
        url = f'https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={self.access_token}'
        data = {'id': id}
        if name is not None:
            data['name'] = name
        if name_en is not None:
            data['name_en'] = name_en
        
        r = requests.post(url=url, json=data)
        assert r.json()['errcode'] == 0

    @pytest.mark.parametrize("id", [2, 3])
    def test_delete_department(self, id):
        url = f'https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={self.access_token}&id={id}'
        
        r = requests.get(url=url)
        assert r.json()['errcode'] == 0


if __name__ == '__main__':
    pytest.main()

"""
作业
企业微信
使用 requests 实现部门的增删改查
"""
import requests


class TestWeworkApi:
    secrete = 'idWKk_dfyLxWept8o0K8nGc15LHZKzmTYsuQSMd9ixcma'
    id = 'maww5c30c081f30784ff'

    def setup(self):
        res = requests.get(
            f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.id}&corpsecret={self.secrete}')
        self.token = res.json()['access_token']
        print(self.token)

    def test_wework_api(self):
        # 获取部门列表
        r = requests.get(f'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.token}&id=2')
        print("获取部门列表")
        print(r.json())
        print(f"Errcode:{r.json()['errcode']}")
        if r.json()['errcode'] == 0:
            # 删除部门
            print("删除部门")
            r = requests.get(
                f'https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={self.token}&id=2')
            print(r.json())

        # 创建部门
        print("创建部门")
        create_data = {
            "name": "广州研发中心",
            "name_en": "RDGZ",
            "parentid": 1,
            "order": 1,
            "id": 2
        }
        r = requests.post('https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=' + self.token,
                          json=create_data)
        print(r.json())

        # 更新部门
        print("更新部门")
        data = {
            "id": 2,
            "name": "广州研发中心new",
            "name_en": "RDGZ_new",
            "parentid": 1,
            "order": 1
        }

        r = requests.post('https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=' + self.token, json=data)
        print(r.json())

test_department.py

import json
import time
import allure
import pytest
import requests
import yaml

# todo:调用httpBase重写
def get_token() -> str:
    with open("./department.yaml") as f:
        d = yaml.safe_load(f)
        id, secret, access_token, last_time = d['id'], d['secret'], d['access_token'], d['last_time']
    now = int(time.time())
    # print(d)
    if now - last_time > 7200:
        url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={id}&corpsecret={secret}'
        r = requests.get(url=url)
        print(r.json())
        d['access_token'] = r.json()['access_token']
        d['last_time'] = now
        # print(d)
        with open("./department.yaml", "w") as f:
            yaml.dump(d, f)
        return d['access_token']
    else:
        return access_token


def yaml_steps(path):
    with allure.step("获取token"):
        access_token = get_token()
    with open(path) as f:
        request = yaml.safe_load(f)
        # print(request)
        for r in request:
            print(r["comment"])
            with allure.step(r["comment"]) :
                params = {"access_token": access_token}
                data = {}
                if r['params'] is not None:
                    for key in r['params'].keys():
                        params[key] = r['params'][key]
                if r['data'] is not None:
                    data = r['data']
                re = requests.request(method=r["method"], url=r["url"], params=params, json=data)
                # if r["method"] == "get":
                #     re = requests.get(url=url, params=params, json=data)
                # if r["method"] == "post":
                #     re = requests.post(url=url, params=params, json=data)
                print(re.json())
                if r['assert'] is not None:
                    for key in r['assert'].keys():
                        assert r['assert'][key] == re.json()[key]


class Test_department:
    def setup(self):
        self.access_token = get_token()

    @pytest.mark.skip
    def test_get_department(self, id=None):
        url = f'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.access_token}'
        if id is not None:
            url = url + f"id={id}"
        r = requests.get(url=url)
        print(r.json())
        assert r.json()["errcode"] == 0

    @pytest.mark.skip
    @pytest.mark.parametrize("name,parentid", [("技术部", 1), ("行政中心", 1)])
    def test_create_department(self, name, parentid):
        url = f"https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.access_token}"
        data = {
            "name": name,
            "parentid": parentid,
        }
        r = requests.post(url=url, data=json.dumps(data))
        print(r.json())
        assert r.json()["errcode"] == 0

    @pytest.mark.skip
    @pytest.mark.parametrize("id,name,name_en", [(2, "技术研发中心", None), (3, "财务部", "caiwu")])
    def test_update_department(self, id, name, name_en):
        url = f'https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={self.access_token}'
        data = {"id": id}
        if name is not None:
            data['name'] = name
        if name_en is not None:
            data['name_en'] = name_en
        r = requests.post(url=url, json=data)
        print(r.json())
        assert r.json()["errcode"] == 0

    @pytest.mark.skip
    @pytest.mark.parametrize("id", [2, 3])
    def test_delete_department(self, id):
        url = f'https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={self.access_token}&id={id}'
        r = requests.get(url=url)
        print(r.json())
        assert r.json()["errcode"] == 0


class Test_Department_withyaml:
    def test_with_yaml(self):
        yaml_steps(path="./testdepartment.yaml")


if __name__ == '__main__':
    pytest.main()

数据驱动文件:
department.py

access_token: sns8sVqcw1NRZsrdNdYVS-hcGhXkWwOTg2PYCG7J2idvPd0xnWe0hZGWixDIkEplZAuoL7HGiIoScZfx-MiOkTVyFptI4ZvMlFD58_JmmxSzf3nbK0VfdQPQNoQ-0YN8L5sLOR97rsxLLhfgtENUPAz9EvDrLYtSYxkBBo82krjfWIcHqg8Uau5JgLK7wE4oad5MP_zEf00rwDneZe3dHA
id: ww6cb5b7542d579ade
last_time: 1589931970
secret: H3vRXGeRKJ-OOypBGMvv0sq87c0aQIgHbzePpPr7bhI

- comment: 获取部门列表
  method: get
  params:
  url: https://qyapi.weixin.qq.com/cgi-bin/department/list
  data:
  assert:
    errcode: 0
    errmsg: ok

- comment: 创建部门
  method: post
  url: https://qyapi.weixin.qq.com/cgi-bin/department/create
  params:
  data:
    "name": 技术部
    "parentid": 1
  assert:
    errcode: 0
    errmsg: created

- comment: 更新部门
  method: post
  url: https://qyapi.weixin.qq.com/cgi-bin/department/update
  params:
  data:
    id: 2
    name: 技术研发中心2
  assert:
    errcode: 0
    errmsg: updated

- comment: 删除部门
  method: get
  params:
    id: 2
  url: https://qyapi.weixin.qq.com/cgi-bin/department/delete
  data:
  assert:
    errcode: 0
    errmsg: deleted
  1. 使用 requests 实现部门的增删改查

https://github.com/ZHHAYO/TestingDemo/blob/master/test_http/test_wework_department.py

import requests


class TestDepartment:

    def setup(self):
        self.ID = 'ww03972ce56e110e69'
        self.SECRET = 'beTIo5nZvPlhqfrh5ZRSW5yMwN-Z53kty082VOeiFas'
        r = requests.get(f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.ID}&corpsecret={self.SECRET}')
        self.ACCESS_TOKEN = r.json()["access_token"]

    def test_department(self):
        # 获取部门
        qr = requests.get(
            f'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.ACCESS_TOKEN}&id=2')
        print(qr.json())
        # 如果部门已经存在,先删除
        if qr.json()['errcode'] == 0:
            # 删除部门
            dr = requests.get(
                f'https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={self.ACCESS_TOKEN}&id=2')
            print(dr.json())

        # 开始创建部门
        data = {
            'name': 'testAdd',
            'parentid': 1,
            'id': '2'
        }
        cr = requests.post(
            f'https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.ACCESS_TOKEN}',
            json=data)
        print(cr.json())
        assert cr.json()['errcode'] == 0

        # 获取部门
        qr = requests.get(
            f'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.ACCESS_TOKEN}&id=[2]')
        print(qr.json())

        # 更新部门
        data = {
            'id': 2,
            'name': 'testUpdate'
        }
        ur = requests.post(f'https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={self.ACCESS_TOKEN}',
                           json=data)
        assert ur.json()['errcode'] == 0
        print(ur.json())

        # 获取部门
        qr = requests.get(
            f'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.ACCESS_TOKEN}&id=[2]')
        print(qr.json())

作业地址

作业地址

https://github.com/tim8709/hogwarts_testing/blob/master/test_requests/api/department.py

企业微信通讯录-部门的增删改查

# !/usr/bin/env python
# _*_ coding:utf-8 _*_
# @author: zhenhualee

import requests
import random


class TestWeworkApi:
    corpid = 'ww6c619306416691d9'
    corpsecret = '2nWlaax4KBCNZZ9N0GNw1LhkpZx3qfBcKLKMlCj02O8'

    def setup(self):
        r = requests.get(
            f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.corpid}&corpsecret={self.corpsecret}")
        # print(r.json())
        self.token = r.json()["access_token"]
        print(r.json()["access_token"])

    def test_wework_member(self):
        return

    def test_wework_depart(self):
        # 获取部门列表
        get_dept = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.token}")
        print(get_dept.json())

        # 删除部门
        dept_id = 11
        res_data = requests.get(
            f"https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={self.token}&id={dept_id}")
        print(res_data.json())

        # 创建部门
        depart_data = {
            "name": "测试使用5",
            "name_en": "test5",
            "parentid": 1,
            "id": 15
        }
        res = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.token}",
                            json=depart_data)
        print(res.json())

        # 更新部门
        updataDepart_data = {
            "id": 12,
            "name": "测试使用3",
            "name_en": "test3",
            "parentid": 1,
            "order": 3
        }

        res_updept = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={self.token}",
                                   json=updataDepart_data)
        print(res_updept.json())

import requests


class TestWeWork():
    def setup(self):
        # 获取token
        ID = "ww4d16179ba163502f"
        SECRET = "_drrVKC8-NzLjeb3IxvkBfxG9_SNF4z2J82v9dHNmMo"
        res = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={ID}&corpsecret={SECRET}")
        self.token = res.json()['access_token']

    def test_edit_department(self):
        # 先去查询部门
        department_name = "potato"
        id = 3
        department_instans = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.token}&id={id}")

        # 创建部门的数据
        department_information = {
            "name": department_name,
            "parentid": 1
        }
        # 判断部门是否已经存在若存在则先删除再创建,若不存在则直接创建
        if department_instans.json()["errcode"] == 0:
            de_res=requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={self.token}&id={id}")
            print(de_res.json())
            cre_res=requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.token}", json=department_information)
            print(cre_res.json())
        else:
            cre_res=requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.token}", json=department_information)
            print(cre_res.json())

        # 修改部门
        modify_data = {
            "id":id,
            "name":"tudousanhao"
        }
        mdf_res = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={self.token}",json=modify_data)
        print(mdf_res.json())

        # 删除部门
        dele_res = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={self.token}&id={id}")
        print(dele_res.json())

        # 获取所有部门查看部门是否还存在
        re = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.token}&id= ")
        print(re.json())

#执行执行结果

class TestRequest():

    def setup_class(self):
        secret = 'G1IFNUioR6z86QbclcYsW1uVkPLLhYm-yMdNUrTlGHE'
        corpid = 'wwed02ee7e67aa4a02'
        url = f' https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}'
        r = requests.get(url)
        self.token = r.json()['access_token']
        

    def test_case1(self):
        name = '部门1'
        # 获取部门列表
        r = requests.get(f'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.token}')
        json_path = f"$.department[?(@.name=='{name}')].id"
        name_id = jsonpath(r.json(), json_path)[0]
        if name_id:
            # 删除部门
            r = requests.get(
                f'https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token={self.token}&id={name_id}')
            print(r.json())
            assert r.json()['errcode'] == 0

        # 新建部门
        data = {
            "name": name,
            "parentid": 1
        }
        r = requests.post(f'https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={self.token}', json=data)
        assert r.json()['errcode'] == 0

        # 更新部门
        r = requests.get(f'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.token}')
        json_path = f"$.department[?(@.name=='{name}')].id"
        name_id = jsonpath(r.json(), json_path)[0]
        data= {
            "id": name_id,
            "name": "部门11"
        }
        r = requests.post(f'https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token={self.token}', json=data)
        assert r.json()['errcode'] == 0

import requests
import pytest

class TestDEP:
    data = {
        'corpid': 'xxxxx',
        'corpsecret': 'xxxxx'
    }
    host = "https://qyapi.weixin.qq.com"

    def setup(self):
        r = requests.get("{}/cgi-bin/gettoken".format(self.host), params=self.data)
        self.token_contact = r.json()["access_token"]

    def test_depart_api(self):
        create_data={
             "name": "江浙沪张敬轩粉丝团",
             "name_en": "hinslove",
             "parentid": 1
        }
        #创建部门
        r1=requests.post(url="{}/cgi-bin/department/create?access_token={}".format(self.host,self.token_contact),json=create_data)
        print(r1.json())

        #更新部门
        update_data={
            "id": 3,
            "name": "江浙沪张敬轩粉丝团",
            "name_en": "hinhinloveme"
        }
        r2=requests.post(url="{}/cgi-bin/department/update?access_token={}".format(self.host,self.token_contact),json=update_data)
        print(r2.json())

        #查询部门
        r3=requests.get(url="{}/cgi-bin/department/list?access_token={}&id={}".format(self.host,self.token_contact,3))
        print(r3.json())
        
        #删除部门
        r4=requests.get(url="{}/cgi-bin/department/delete?access_token={}&id={}".format(self.host,self.token_contact,3))
        print(r4.json())

ps:有种时隔多年终于交作业的感觉

https://github.com/Ashley-luo66/hogwarts_lagou_homework/blob/master/requests_homework/requests_1/test_dep.py

https://github.com/hehe1523233/selenium/blob/master/test_wx.py

https://github.com/whiteParachute/PythonTest/blob/master/test_requests/test_wework_api.py