python + selenium + unittest 自动化测试框架 -- 入门篇
、 预置条件:
1. python已安装
2. pycharm已安装
3. selenium已安装
4. chrome.driver 驱动已下载
二、工程建立
1. New Project:建立自己的工程
2. New Package:建立各个配置包
3. New Python:建立python脚本
三、上代码:
1. constant.py
将相对独立的常量单独封装到此处,便于后期修改。
2. test_login_case.py
# -*- coding:utf-8 -*-
'''
@project: Voctest
@author: Jimmy
@file: test_case_login.py
@ide: PyCharm Community Edition
@time: 2018-10-31 16:44
@blog: https://www.cnblogs.com/gotesting/
'''
from Element.constant import *
from time import sleep
import selenium
import unittest
class LoginCase(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
# 定义登录方法
def login(self,username,password):
self.driver.get(login_url)
self.driver.find_element_by_class_name('gd-login-user').send_keys(username)
self.driver.find_element_by_class_name('gd-login-password').send_keys(password)
self.driver.find_element_by_class_name('gd-login-submit-bg').click()
# 正确用户名密码登录
def test_login_success(self):
self.login('system','123456')
sleep(2)
title_msg = self.driver.find_element_by_class_name('gd-topbar-name-text').text
self.assertEquals('首页',title_msg)
self.driver.get_screenshot_as_file('F:\python\Voctest\Picture\login_success.png')
# 用户名为空登录
def test_login_username_null(self):
self.login('','123456')
sleep(2)
login_msg = self.driver.find_element_by_class_name('gd-login-submit-text').text
self.assertIn('登 录',login_msg)
self.driver.get_screenshot_as_file('F:\python\Voctest\Picture\login_username_null.png')
# 密码为空登录
def test_login_password_null(self):
self.login('system','')
sleep(2)
login_msg = self.driver.find_element_by_class_name('gd-login-submit-text').text
self.assertIn('登 录',login_msg)
self.driver.get_screenshot_as_file('F:\python\Voctest\Picture\login_password_null.png')
# 错误用户名密码登录
def test_login_fail(self):
self.login('system','12345678')
sleep(2)
login_msg = self.driver.find_element_by_class_name('gd-login-msg').text
self.assertEquals('用户名或密码错误',login_msg)
self.driver.get_screenshot_as_file('F:\python\Voctest\Picture\login_password_fail.png')
def tearDown(self):
sleep(2)
print('login auto test done !')
self.driver.quit()
if __name__ == '__main__':
unittest.main()