自动化测试注册接口,如何生成大量临时邮箱和获取邮箱验证码

背景

编写自动化测试脚本验证服务接口和业务流程是否正常是必不可少的监控步骤, 但是现在很多注册接口需要使用邮箱来注册,并校验邮箱验证码,这应该如何实现自动测试?
主要难点在于如何生成大量临时邮箱(因为每次注册一个账号后该邮箱就不可再用了),还有如何自动获取邮件中的验证码.下面使用了免费的临时邮箱http://24mail.chacuo.net/网站来获取临时邮箱,调用获取邮件内容的接口正则匹配检索6位验证码

代码

下面是Python代码, 利用pytest作为测试框架,根据实际修改调用自己的发送验证码接口和注册接口

from pytest import mark
import logging
from retrying import retry
import requests, re, json
from lxml import etree

email_address_url = 'http://24mail.chacuo.net/'


class TestRegister:
    def setup_method(self, method):
        # 初始化
        self.test_init = 'test init'

    def test_register(self):
        session = requests.Session()
        page = session.get(email_address_url)
        email_address_prefix = etree.HTML(page.text).xpath("//input[@id='converts']/@value")
        email_address_net = email_address_prefix[0]+'@chacuo.net'
        logging.info('1. get temp email_address: %s' % email_address_net)

        # 调用自己的服务接口,发送邮箱注册码
        logging.info('2. send register email code')
        # params = {'email': email_address_net, 'type': "register"}
        # resp = self.form_post("api/sendEmailCode", params)
        # assert resp.json()['code'] == 200

        email_code = self.get_email_code(email_address_net, email_address_prefix, session)
        logging.info('3. get register email_code: %s' % email_code)

        logging.info('4. register user')
        # 调用自己的服务注册接口
        # resp = self.post('api/emailRegist', data={
        #     'username': email_address_net,
        #     'password': '123456',
        #     'emailcode': email_code,
        # })
        # assert resp.json()['code'] == 200

    # helper method
    def get_email_code(self, email_address, session):
        data = {'data': email_address[0], 'type': 'set', 'arg': 'd=chacuo.nef_f='}
        session.post(email_address_url, data=data)

        # refresh email
        data = {'data': email_address[0], 'type': 'refresh', 'arg': ''}
        mid = self.refresh_email(session, data)

        # retrieves email_code from email info
        data = {'data': email_address[0], 'type': 'mailinfo', 'arg': 'f='+str(mid)}
        mail_info = session.post(email_address_url, data=data)
        email_code = re.findall(r'>(\d+)<', str(mail_info.text))
        return email_code[0]

    # retry refresh to receive email
    @retry(stop_max_attempt_number=10, wait_fixed=2000)
    def refresh_email(self, session, data):
        refresh = session.post(email_address_url, data=data)
        content = json.loads(refresh.text)
        if len(content['data'][0]['list']) > 0:
            return content['data'][0]['list'][0]['MID']
        raise Exception('no receive email_code')

在测试过程中,发现国内通过阿里云邮件服务发送的邮件到不了该临时邮箱,国外AWS邮件服务则可正常发送邮件到该临时邮箱,这点需要注意.

你可能感兴趣的:(python,邮箱注册,自动测试注册,注册获取邮箱验证码,python)