import os.path
import requests
import ddddocr
# 创建一个session实例
session = requests.session()
# 实例化
ocr = ddddocr.DdddOcr()
ver_code_url = "http://192.168.0.105/index.php/Home/User/verify/type/user_reg.html"
resp_v = session.get(url=ver_code_url)
# 图片目录
code_picture_path = os.path.dirname(__file__) + '/picture'
# 验证码图片路径
picture_file = os.path.join(code_picture_path, 'captcha.png')
# 如果目录不存在,创建目录
if not os.path.exists(code_picture_path):
os.makedirs(code_picture_path)
# 保存图片到指定路径
with open(picture_file, 'wb') as f:
f.write(resp_v.content)
print(f'验证码图片已保存{picture_file}')
# 打开图片,读取 识别验证码
with open(picture_file, 'rb') as f:
image_bytes = f.read()
res = ocr.classification(image_bytes)
print(res)
# 注册接口
regist_url = "http://192.168.0.105/Home/user/reg.html"
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"scene": "1",
"username": "18270000000",
"verify_code": res,
"password": "123456",
"password2": "123456",
"invite": ""
}
resp_regist = session.post(url=regist_url, headers=headers, data=data)
print("注册结果为:", resp_regist.json())
import os.path
import unittest
import requests
import ddddocr
class TestTpShopRegist(unittest.TestCase):
def setUp(self):
# 实例化session
self.session = requests.session()
# 实例化
self.ocr = ddddocr.DdddOcr()
# 验证码url
self.ver_code_url= "http://192.168.0.105/index.php/Home/User/verify/type/user_reg.html"
# 注册url
self.regist_url = "http://192.168.0.105/Home/user/reg.html"
self.headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
def tearDown(self):
# 关闭session
self.session.close()
# 将session实现注册的代码拷贝到框架中
def test01_regist(self):
# 使用session发送获取验证码的请求
# ver_code_url = "http://192.168.0.105/index.php/Home/User/verify/type/user_reg.html"
resp_v = self.session.get(url=self.ver_code_url)
# 断言响应头中包函 image
self.assertIn('image',resp_v.headers.get('Content-Type'))
# 验证码图片目录路径
code_picture_path = os.path.dirname(__file__) + '/picture'
# 验证码图片路径
picture_file = os.path.join(code_picture_path, 'captcha.png')
# 如果验证码图片目录不存在,新建目录
if not os.path.exists(code_picture_path):
os.makedirs(code_picture_path)
# 保存图片
with open(picture_file, 'wb') as f:
f.write(resp_v.content)
print(f'图片已保存{picture_file}')
# 读取图片
with open(picture_file, 'rb') as f:
image_bytes = f.read()
# 识别图片
res_code = self.ocr.classification(image_bytes)
print(f'验证码识别结果为:{res_code}')
# 注册接口
# regist_url = "http://192.168.0.105/Home/user/reg.html"
# headers = {
# "Content-Type": "application/x-www-form-urlencoded"
# }
data = {
"scene": "1",
"username": "18270000000",
"verify_code": res_code,
"password": "123456",
"password2": "123456",
"invite": ""
}
resp_regist =self.session.post(url=self.regist_url, headers=self.headers, data=data)
# 断言响应状态码 200
self.assertEqual(200,resp_regist.status_code)
# 断言 响应体状态 status 1
self.assertEqual(1, resp_regist.json().get('status'))
# 断言 响应体 msg 登录成功
self.assertEqual('注册成功', resp_regist.json().get('msg'))
# 打印注册结果
print("注册的结果为:", resp_regist.json())
if __name__ == '__main__':
unittest.main()