• docker 实战课程贴 at August 31, 2019

  • caps = {
    "platformName": "Android",
    "deviceName": "MuMu",
    "noReset": "True",
    "appPackage": "com.xueqiu.android",
    "appActivity": ".view.WelcomeActivityAlias",
    "automationName": "UiAutomator2",
    "autoGrantPermissions": "true"
    }
    driver = webdriver.Remote('http://localhost:4723/wd/hub', caps)
    driver.implicitly_wait(10)

    search_button = driver.find_element_by_id("com.xueqiu.android:id/tv_search")
    search_button.click()
    driver.implicitly_wait(3)

    search_info = driver.find_element_by_id("com.xueqiu.android:id/search_input_text")
    search_info.send_keys("alibaba")
    driver.implicitly_wait(3)

    alibaba = driver.find_element_by_id("com.xueqiu.android:id/follow_btn")
    alibaba.click()
  • '''
    1.设计一个表示服务器的类。包含服务器的属性有:CPU个数,内存大小,磁盘空间大小,操作系统类型(Linux, Windows)。其中操作系统类型设置为私有变量,外部不可以更改。实现一个方法,输出服务器的属性内容为以下格式:8 CPU 40G 内存,150G 磁盘空间,Linux
    '''
    class Sever(object):
    def __init__(self,cpu_count,memory,disk,OS):
    self.cpu_count = cpu_count
    self.memory = memory
    self.disk = disk
    self.__OS = OS #私有变量

    def get_server_info(self):
    print('服务器参数:CPU%s,内存%s,磁盘空间:%s,操作系统:%s'%(self.cpu_count,self.memory,self.disk,self.__OS))

    '''
    2.设计一个作业1中服务器的子类,实现一个新的方法,根据cpu个数,内存大小,磁盘空间大小计算出服务器当前价格 在子类里面实现一个服务价格的函数。计算公式为: CPU 个数* 1527.679+内存大小G* 100.21+磁盘空间大小G* 50.789 返回数据类型为浮点型。保留小数点后2 并实例化此方法,打印出价格。
    '''
    class MyServer(Sever):
    def __init__(self,cpu_count,memory,disk,OS):
    Sever.__init__(self, cpu_count, memory, disk, OS)

    def get_server_price(self):
    cpu_price = self.cpu_count*1527.679
    memory_price = self.memory*100.21
    disk_price = self.disk*50.789
    server_price = cpu_price+memory_price+disk_price
    print('%.2f'%server_price)
    return '%.2f'%server_price
    server = MyServer(8,40,150,'linux')
    server.get_server_info()
    server.get_server_price()

    '''
    3.对下面测试方法使用pytestrerun, 参数化方法来实现自动化测试
    def bubble_sort(nums):
    for i in range(len(nums)-1):
    for j in range(len(nums)-i-1):
    if nums[j] > nums[j+1]:
    nums[j], nums[j+1] = nums[j+1], nums[j]
    return random.choice([nums, None, 10])
    '''
    import random
    import pytest

    data = [([1,2,3,4,5]),
    ([0,0,1,2,3,3]),
    ([11,22,33,44,55,66])]

    def bubble_sort(nums):
    for i in range(len(nums)-1):
    for j in range(len(nums)-i-1):
    if nums[j] > nums[j+1]:
    nums[j], nums[j+1] = nums[j+1], nums[j]
    return random.choice([nums,None,10])

    def bubble_sort_new(nums):
    for i in range(len(nums)-1):
    for j in range(len(nums)-i-1):
    if nums[j] > nums[j+1]:
    nums[j], nums[j+1] = nums[j+1], nums[j]
    return nums

    @pytest.mark.parametrize("nums",data)
    def test_bubble_sort(nums):
    assert bubble_sort(nums) == bubble_sort_new(input)

    pytest --reruns 5 test_demo.py

  • #练习一: 使用unittest 完成自动化测试并使用HttpTestRunner生成报告
    '''
    1、写个简单的计算器功能,大小写转换功能,随机生成字符串功能
    2、编写测试用例,不同的数据(你能想到的所有测试用例),并进行断言。除0的选择可以跳过skip,随机生成字符串功能可以断言是否包含你名字的缩写。
    3、使用unittest框架+HTMLTestRunner,最后生成html报告
    '''
    import unittest
    import os
    import time
    import logging
    import ddt
    from HTMLTestRunner import HTMLTestRunner
    import random

    testData1 = [{'a':5,'b':1,'x':'+','result':6},
    {'a':5,'b':1,'x':'-','result':4},
    {'a':5,'b':1,'x':'*','result':5},
    {'a':5,'b':1,'x':'/','result':5}
    ]
    testData2 = [{'string':'asd','stringType':'upper','result':'ASD'},
    {'string': 'ASD', 'stringType': 'lower','result':'asd'}
    ]

    #被测函数
    class test_demo():
    def jisuanqi(a,x,b):
    if x == '+':
    return a+b
    elif x =='-':
    return a-b
    elif x == '*':
    return a*b
    elif x == '/':
    return a/b
    else:
    logging.info('只支持数字加减乘除四则运算')

    def translation(string,stringType):
    if stringType == 'lower':
    return string.lower()
    elif stringType == 'upper':
    return string.upper()
    else:
    print('ERROR:只支持大小写类型转换')


    def random_string(num):
    return random.random(num)


    #测试函数
    @ddt.ddt
    class TestCases(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
    print('整个测试类运行前执行')

    def setUp(self):
    print("每个测试方法执行前运行一次")

    def tearDown(self):
    print("每个测试方法执行完后运行一次")

    @ddt.data(*testData1)
    def test_case_jisuanqi(self,data):
    result = test_demo.jisuanqi(data['a'],data['x'],data['b'])
    assert result == data['result']

    @ddt.data(*testData2)
    def test_case_translation(self,data):
    result = test_demo.translation(data['string'],data['stringType'])
    assert result == data['result']

    def test_case_randomString(self):
    pass

    @classmethod
    def tearDownClass(cls):
    print("整个测试类运行完成后执行一次")


    #测试报告
    if __name__ == '__main__':
    report_path = os.path.join(os.path.dirname(__file__), 'report')
    now = time.strftime("%Y-%m-%d %H_%M_%S", time.localtime())
    filename = report_path + "/" + now + "_result.html"
    print('******************************************')
    suite = unittest.TestSuite()
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestCases))
    with open(filename, 'wb') as fp:
    runner = HTMLTestRunner(
    stream=fp,
    title='测试报告',
    description='测试用例')
    runner.run(suite)

    #练习二:使用pytest完成自动化测试并用allure生成测试报告
    '''
    建立一个登陆模块的测试用例,一个人力资源模块的测试用例,其中包括增删改查4个小功能,查询不需要登陆。
    使用pytest,allure的方式,技术上要有登陆依赖用Fixtureconftest实现,要添加人员时有参数化,数据驱动,
    使用文件或list/dict的方式传入数据。通过allure的添加附加信息,及各种信息包括feature,story,step,attach,title,discription等。
    '''
    conftest.py
    @pytest.fixture(scope = 'module')
    def test_login(request):
    user = request.param['user']
    password = request.param['password']
    if user != 'linda':
    print('用户名错误')
    elif password != '888888':
    print('密码错误')
    else:
    print('登陆成功')

    yield # 模块执行完case 在最后执行一遍teardown操作。

    print('执行teardown')
    print('推出登陆')

    Pytest.py
    import allure
    import pytest
    import os
    import subprocess

    test_user_data = [{"user": "linda", "password": "888888"}]

    test_user_data1 = [{"user": "linda", "password": "888888"},
    {"user": "servenruby", "password": "123456"},
    {"user": "linda", "password": "123456"}]

    test_user_data2 = [{"name": "中国平安", "money": 999, "country": 'china'},
    {"name": "阿里巴巴", "money": 888, "country": 'jepan'},
    {"name": "拼多多", "money": 666, "country": 'USA'}]

    @allure.feature('测试登录模块')
    @pytest.mark.run(order = 1) #第一个执行
    @pytest.mark.parametrize('test_login', test_user_data1, indirect=True)
    class TestLogin():
    def test_login_case1(self,test_login):
    assert 1 == 1

    @allure.feature('测试人事模块')
    @pytest.mark.parametrize('test_login', test_user_data, indirect=True)
    class TestPersion():

    @allure.story('测试用例:新增人员')
    @pytest.mark.parametrize('data',test_user_data2)
    def test_persion_add(self,test_login,data):
    with allure.step("步骤1"):
    allure.attach('说明')
    print('新增用户%s'%data['name'])

    @allure.story('测试用例:删除新增的人员')
    @pytest.mark.parametrize('data',test_user_data2)
    def test_persion_del(self,test_login,data):
    print('删除用户%s'%data['name'])

    558 pytest -v -s PyTest.py --alluredir=./result/
    559 allure serve ./result/

  • # 利用pip, 安装第三方模块requests, 描述你用什么方法来确认安装是成功的。
    print('进入python环境,导入requests模块,导入成功.')
    # 2.918 转化为整形
    a = 2.918
    print(int(a))

    # 10 进制数 18 转化为2进制数
    print(bin(18))

    # java 替换字符串:”Python is popular 里面的Python,并 java 变换成JAVA
    print('Python is popular'.replace('Python','java'.upper()))

    # 把列表 [1, 2, 3,4 5,6,7,8]里面的2, 4, 6,8 打印出来
    list = [1, 2, 3,4,5,6,7,8]
    print([x for x in list if x%2==0])

    # 创建一个字典,字典的key分别是name, sex, province , 修改原始province 的值 为新值”江苏”
    dicts = {'name':'zhangsan', 'sex':'man', 'province':'shanghai'}
    dicts['province'] = 'jiangsu'
    print(dicts)

    Test_str="Python was created in 1989, Python is using in AI, big data, IOT."
    #按下列要求对上面文字做出处理。
    # 把上面文字中的所有大写转化为小写
    print(Test_str.lower())

    # 把这段话每个单词放到列表里面,不能包含空格。
    new_str = Test_str.replace(',','').replace(' ','|')
    print(new_str.split('|'))

    # 把列表最中间的一个单词打印出来。
    print(new_str[int(len(new_str)/2)])

    # 2.List1=[python, 5,6, 8], list2=[python,5, 6, 8,10], list1list2做出如下处理:
    # 把上面2list的内容合并成一个
    List1=["python",5,6,8]
    List2=["python","5",6,8,10]
    print(List1+List2)

    # 利用set里面的方法,对合并后的list 去除重复元素。最 后输出是还是list =python, 5,6, 8,5,10
    set1=set(List1+List2).difference()
    print(str(set1))

    # 实现一个函数,要求对一个列表里面所有数字求和,如果里 面含有非数字的元素。直接跳过。比如[1,2,3] 输出是5 如果 [1,2,4,a] 输出是7 并在另外一个包(目录)里面调用这个 函数
    def fo(*args):
    sum = 0
    if len(args)>=1:
    for arg in args:
    if type(arg) == int:
    sum = sum+arg
    else:
    continue
    else:
    print("无参数")
    print(sum)

    fo(1,2,3,'qwe')

    # 实现一个不定长参数的函数def flexible(aa, *args, **kwargs):
    # 把传入的参数和值打印出来。比如传入参数是
    def flexible(*args, **kwargs):
    print(args,kwargs)
    flexible(2, 3, x = 4, y = 5, *[1, 2, 3], **{'a':1,'b': 2})
    # 输出结果:(2, 3, 1, 2, 3){'a': 1, 'y': 5, 'b': 2, 'x': 4}
    # 面试题:*args, **kwargs 有什么作用

    print('*args, **kwargs主要用于将不定长参数传递给函数。*args将传递的参数打包成元组形式, **kwargs将传递的参数打包成字典形式')
  • import logging
    import pytest
    import requests
    import json
    class TestXueqiu(object):
    logging.basicConfig(level=logging.INFO)
    def test_xueqiu_quote(self):
    url = 'https://stock.xueqiu.com/v5/stock/portfolio/stock/list.json'
    data = {'category':'1',
    'pid':'-1',
    'size':'10000',
    'x':'1.3',
    'page':'1'}
    headers = {'User-Agent':'Xueqiu Android 11.19'}
    cookies = {'xq_a_token':'5806a70c6bc5d5fb2b00978aeb1895532fffe502',
    'u':'3446260779'}
    r1 = requests.get(url,
    params=data,
    headers=headers,
    cookies=cookies
    )
    logging.info(json.dumps(r1.json(),indent=4))
  • curl 'https://www.baidu.com' -H 'lalalalalal@testerhome' -vvv

  • ...

  • 第十期_SQL_20190704 at July 04, 2019

    wangjianqingdeMacBook-Air:~ wangjianqing$ mysql -h docker.testing-studio.com -P 3306 -u hogwarts -phogwarts -D employees -e "select AVG(salary) from (select * from salaries order by salary desc limit 100) as NewTable;"
    mysql: [Warning] Using a password on the command line interface can be insecure.
    +-------------+
    | AVG(salary) |
    +-------------+
    | 148999.9600 |
    +-------------+