9. 框架优化-3 post接口

2024-02-14  本文已影响0人  薛东弗斯
# project > data > data.yaml
json_data: { title: foo,body: bar,userId: 1 }
# project > config > setting.ini
[host]
# api_sit_url = https://api.binstd.com
api_sit_url = https://jsonplaceholder.typicode.com
# project > api > api.py
from core.api_util import api_util


def mobile_query(params):
    response = api_util.get_mobile_belong(params=params)
    return response.json()


def try_json(json_data):
    """
    This method is to test json parameters
    :param json_data:
    :return:
    """
    response = api_util.post_data(json=json_data)
    return response.json()

# project > test_cases > test_post.py
import pytest
from api.api import try_json
from utils.read_test import base_data


def test_post():
    json_data = base_data.read_data()['json_data']
    result = try_json(json_data)
    print(result)
    assert result['id'] == 101


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

# project > core > rest_client.py
import requests

from utils.read_test import base_data

api_root_url = base_data.read_ini()['host']['api_sit_url']


class RestClient:
    def __init__(self):
        self.api_root_url = api_root_url

    def get(self, url, **kwargs):
        return requests.get(self.api_root_url + url, **kwargs)

    def post(self, url, **kwargs):
        return requests.post(self.api_root_url + url, **kwargs)

# project > core > api_util.py
from core.rest_client import RestClient


class Api(RestClient):
    def __init__(self):
        super().__init__()

    def get_mobile_belong(self, **kwargs):
        return self.get('/shouji/query', **kwargs)

    def post_data(self, **kwargs):
        return self.post('/posts', **kwargs)

api_util = Api()

# project > utils > read_test.py
import yaml
import configparser
import os

current_path = os.path.realpath(__file__)
parent_path = os.path.dirname(current_path)
data_path = os.path.join(os.path.dirname(parent_path), "data", "data.yaml")
ini_path = os.path.join(os.path.dirname(parent_path), "config", "setting.ini")


class FileRead:
    def __init__(self):
        self.data_path = data_path
        self.ini_path = ini_path

    def read_data(self):
        f = open(self.data_path, encoding="utf8")
        data = yaml.safe_load(f)
        return data

    def read_ini(self):
        config = configparser.ConfigParser()
        config.read(self.ini_path, encoding='utf8')
        return config


base_data = FileRead()

上一篇 下一篇

猜你喜欢

热点阅读