IDLE介绍
快捷键介绍: ?? ?单注释 ? ?shift + 3 ? ?? ?双注释 ? ?alt + 3 ? ?? ?取消双注释 ?alt + 4 ?? ?回退 ?ctrl + z? 1.程序运行前先报存 2.运行的快捷键 F5 或者 Run ? 3.运行我们的第一个程序 print 是python内置的一个函数 ?代表的是打印输出print后面的内容输出到终端 print "helloworld"
Python运行的三种模式: ?? ?1.交互模式 ?? ??? ?类似出现>>>的这种模式,一般cmd-python--进到python的交互模式 ?? ??? ?idle--自带的交互模式 ?? ?2.编辑器模式 ?? ??? ?类似笔记本,但是笔记本功能强大。 ?? ??? ?比如说自带IDLE/Pycharm/eclipse/sublime text 2或者3/Linux vi 都可以用来写代码 ?? ?3.脚本模式 ?? ??? ?可以的通过命令执行python文件 ?? ??? ?第一步:cmd --->再切换到python文件所在目录?? ? ?? ??? ?第二步:python ?demo.py(demo.py是python文件) 一、变量? 1.变量定义 ?? ?在python中,变量是一个值。比如 a = 1 ?这个a就是一个变量。 ?? ?a ?= 10 ?? ?b ?= 30 ?? ?z ?= a+b? >>> a = 1 ? ? a是变量名 ?=号赋值号 ? 1是变量的值 2.变量的赋值 ?? ?变量赋值的过程就是创建变量的过程,变量一定要先定义才可以被引用。 ?? ?变量的类型由值决定。
a.普通赋值 ? a = 1? b.链式赋值 ? a = b = c ?=1 c.序列解包赋值 a,b,c,d=1,2,3,4? 3.变量的命名规范 ?? ?a.不可以以数字开头 ?? ?>>> 456name=90 ?? ? ?File "<stdin>", line 1 ?? ? ? ?456name=90 ?? ? ? ? ? ? ?^ ?? ?SyntaxError: invalid syntax ?? ?>>> name456.=90 ?? ? ?File "<stdin>", line 1 ?? ? ? ?name456.=90 ?? ? ? ? ? ? ? ?^ ?? ?SyntaxError: invalid syntax ?? ?>>> name456=90 ?? ?>>> name456 ?? ?90 ?? ?>>> name_123=89 ?? ?>>> name_123 ?? ?89 ?? ?b.不可以以系统关键字命名 and ?or ?if ?while ?class ?for def unittest ... ?? ?>>> and=67 ?? ? ?File "<stdin>", line 1 ?? ? ? ?and=67 ?? ? ? ? ?^ ?? ?SyntaxError: invalid syntax ?? ?>>> if=90\ ?? ? ?File "<stdin>", line 1 ?? ? ? ?if=90\ ?? ? ? ? ?^ ?? ?SyntaxError: invalid syntax ?? ?>>> if=90 ?? ? ?File "<stdin>", line 1 ?? ? ? ?if=90 ?? ? ? ? ?^ ?? ?SyntaxError: invalid syntax ?? ?>>> class=90 ?? ? ?File "<stdin>", line 1 ?? ? ? ?class=90 ?? ?c.不可以以特殊字符开头 ?? ?d.可以包含字母、下划线、数字
二、Python常用的几种数据类型 ?? ?1.整型 ? ? int? ?? ?2.浮点型 ?float? ?? ?3.空值 ? ? None? ?? ?4.布尔值 ?True False ?? ?5.字符串 ?str?
查看变量类型的函数是:type(变量) ?? ??? ? ? ? ? ? ? isinstance(a,b) ?a代表的是变量 ?b代表的是变量的类型 演示: ?? ?>>> age=100 ?? ?>>> type(age) ?? ?<type 'int'> ?? ?>>> age=100. ?? ?>>> age=100.00 ?? ?>>> type(age) ?? ?<type 'float'> ?? ?>>> age=None ?? ?>>> type(age) ?? ?<type 'NoneType'> ?? ?>>> age=True ?? ?>>> type(age) ?? ?<type 'bool'> ?? ?>>> age=False ?? ?>>> type(age) ?? ?<type 'bool'> ?? ?>>> age='100' ?? ?>>> type(age) ?? ?<type 'str'>
?isinstance的用法: ?? ?>>> isinstance('',int) ?? ?False ?? ?>>> isinstance('',str) ?? ?True ?? ?>>> isinstance(123,str) ?? ?False ?? ?>>> isinstance(123,int) ?? ?True ?? ?>>> isinstance(123,str) ?? ?^C 常用的数据类型之间的转换 ?? ?>>> demo = 123 ?? ?>>> float(demo) ?? ?123.0 ?? ?>>> str(demo) ?? ?'123' ?? ?>>> demo ?? ?123 ?? ?>>> demo = 'zhangshan' ?? ?>>> int(demo) ?? ?Traceback (most recent call last): ?? ? ?File "<stdin>", line 1, in <module> ?? ?ValueError: invalid literal for int() with base 10: 'zhangshan' ?? ?>>> float(demo) ?? ?Traceback (most recent call last): ?? ? ?File "<stdin>", line 1, in <module> ?? ?ValueError: could not convert string to float: zhangshan
#####数据结构之--字符串(str)详解##### ?? ?1.字符串定义和创建 ?? ??? ?字符串是以引号包围,有序,不可变得序列(凡是可以通过索引取值的都是:序列)之一。 ?? ?'' ?? ?"" ?? ?""" 或者 ''' ?? ?a.字符串可以嵌套使用,不可以交叉使用。 ?? ?b."""经常用于多行的注释 ?? ?2.特点 ?? ??? ?a.有序 ?? ??? ?b.不可变 ? (不可变对象在调用自身方法时,不会改变原有值) ?? ??? ?c.序列?? ??? ?
?? ?3.字符串中的\转义字符 ?? ?>>> demo = "let's go jim!" ?? ?>>> demo ?? ?"let's go jim!" ?? ?>>> demo = 'let\'s go jim!' ?? ?>>> demo ?? ?"let's go jim!"
?? ?\n换行符? ?? ?>>> print """asdfdasfsa ?? ?... asdfsa ?? ?... asdfasdf ?? ?... asdf ?? ?... """ ?? ?asdfdasfsa ?? ?asdfsa ?? ?asdfasdf ?? ?asdf
?? ?>>> '''asdfdasfasfasdfsda''' ?? ?'asdfdasfasfasdfsda' ?? ?>>> '''asdfdasfasfasdfsda''' ?? ?'asdfdasfasfasdfsda' ?? ?>>> '''asdfdasfasfasdfsda ?? ?... dasfasdf ?? ?... asdfdas ?? ?... asdfas ?? ?... ''' ?? ?'asdfdasfasfasdfsda\ndasfasdf\nasdfdas\nasdfas\n'
?? ?4.字符串之--原始字符串 ?r ?? ?>>> 'C:\now' ?? ?'C:\now' ?? ?>>> print 'C:\now' ?? ?C: ?? ?ow ?? ?>>> print 'C:\\now' ?? ?C:\now ?? ?>>> print 'C:\\now\\user\\bin\\env\\python\\soft' ?? ?C:\now\user\bin\env\python\soft ?? ?>>> print r'C:\now\user\bin\env\python\soft' ?? ?C:\now\user\bin\env\python\soft
?? ?5.字符串拼接 (通过加号+拼接) ?? ?>>> age = '15' ?? ?>>> name + age ?+ 'nine?' ?? ?'zhangshan15nine?' ?? ?>>> age = 15 ?? ?>>> name = 'zhangshan' ?? ?>>> name + str(age) + 'nine?' ?? ?'zhangshan15nine?' ?? ?>>> name + str(age) + 'nine?' + 'hello' ?? ?'zhangshan15nine?hello' ?? ?>>>
?? ?6.字符串格式化输出 ?(%格式化输出操作 ? ?%s替换所有类型 ? ? %d替换的是整型 ? %f替换的是浮点型 ?.....) ?? ?>>> name = 'wanguolin111' ?? ?>>> age = 250 ?? ?>>> 'hello,jim,my name is %s,my age is %d'%name,age ?? ?Traceback (most recent call last): ?? ? ?File "<stdin>", line 1, in <module> ?? ?TypeError: not enough arguments for format string ?? ?>>> 'hello,jim,my name is %s,my age is %d'%(name,age) ?? ?'hello,jim,my name is wanguolin111,my age is 250'
?? ?7.字符串复制 *? ?? ?>>> 'hello'*10 + 'welcome to china' ?? ?'hellohellohellohellohellohellohellohellohellohellowelcome to china'
?? ?8.字符串索引 ?? ??? ?a.索引的默认取值方向是从左到右 ?? ??? ?b.索引从0开始 ,第一个字符的索引位是0
?? ?#####单个取值##### ?? ?>>> demo = 'hello_world' ?? ?>>> demo ?? ?'hello_world' ?? ?>>> demo = 'hello_world' ?? ?>>> demo[0] ?? ?'h' ?? ?>>> demo[1] ?? ?'e' ?? ?>>> demo[10] ?? ?'d'
?? ?#####普通截取##### 格式: [开始端:结尾端] ? 包含开始端,不包含结尾端 ?? ?>>> demo ?? ?'hello_world' ?? ?>>> demo[0:4] ?? ?'hell' ?? ?>>> demo[0:5] ?? ?'hello' ?? ?>>> demo ?? ?'hello_world' ?? ?>>> demo[:] ? #截取所有? ?? ?'hello_world' ?? ?>>> demo[0:] ?? ?'hello_world'
?? ?#####步长截取##### ? 格式: [开始端 : 结尾端 : 步长值] ? 包含开始端,不包含结尾端,步长值按照步长减一隔取 ?? ?>>> demo ?? ?'hello_world' ?? ?>>> demo[0:4] ?? ?'hell' ?? ?>>> demo[0:5] ?? ?'hello' ?? ?>>> demo ?? ?'hello_world' ?? ?>>> demo[:] ?? ?'hello_world' ?? ?>>> demo[0:] ?? ?'hello_world' ?? ?>>> demo[::] ?? ?'hello_world' ?? ?>>> demo[::2] ?? ?'hlowrd' ?? ?>>> demo[::3] ?? ?'hlwl' ?? ?>>> demo[::4] ?? ?'hor'
?? ?#####反向截取##### ?? ?>>> demo ?? ?'hello_world' ?? ?>>> demo[10] ?? ?'d' ?? ?>>> demo[-1] ?? ?'d' ?? ?>>> demo[-2] ?? ?'l' ?? ?>>> demo[-3] ?? ?'r' ?? ?>>> demo[-3:-1] ?? ?'rl' ? ??
?? ?#####特殊取值的几种情况##### ?? ?>>> demo[1:5] ?? ?'ello' ?? ?>>> demo[5:1] ? #取值为空的几种情况? ?? ?'' ?? ?>>> demo[-1:-5] ?? ?'' ?? ?#####将字符串进行反转输出##### ?? ?>>> demo[::-1] ?? ?'dlrow_olleh'
?? ?9.字符串的判断 ?? ?>>> 'e' in demo ?? ?True ?? ?>>> 'e' not ?in demo ?? ?False
?? ?10.字符串常用内置函数 ?? ?dir(str) ?查看字符串的用法 ?? ??? ?1.字符串-find()函数 ?? ??? ?>>> demo = 'hello,wanguolin,my name is bob'.find('e') ?? ??? ?>>> 'hello,wanguolin,my name is bob'.find('e') ?? ??? ?1 ?? ??? ?>>> 'hello,wanguolin,my name is bob'.find('c') ?? ??? ?-1 ?? ??? ?>>> 'hello,wanguolin,my name is bob'.find('ee') ?? ??? ?-1 ?? ??? ?>>> 'hello,wanguolin,my name is bob'.find('') ?? ??? ?0 ?? ??? ?>>> 'hello,wanguolin,my name is bob'.find('b') ?? ??? ?27
?? ??? ?2.字符串-split()函数(分隔函数) ?? ??? ?>>> demo='hello,wanguolin,my name is bob' ?? ??? ?>>> demo.split('e') ?? ??? ?['h', 'llo,wanguolin,my nam', ' is bob'] ?? ??? ?>>> demo='www.baidu.com' ?? ??? ?>>> demo.split('baidu') ?? ??? ?['www.', '.com'] ?? ??? ?>>> demo.split('baidu')[0] ?? ??? ?'www.' ?? ??? ?3.字符串-upper()函数 ?将字符串中所有的字符变成大写 ?? ??? ?>>>demo='www.baidu.com' ?? ??? ?>>> demo ?? ??? ?'www.baidu.com' ?? ??? ?>>> demo.upper() ?? ??? ?'WWW.BAIDU.COM'
?? ??? ?>>> demo1 = demo.upper() ?? ??? ?>>> demo1 ?? ??? ?'WWW.BAIDU.COM' ?? ??? ?>>> ?? ??? ?>>> demo ?? ??? ?'www.baidu.com' ?? ??? ?>>> demo1 ?? ??? ?'WWW.BAIDU.COM'
?? ??? ?4.字符串-lower()函数 ? 将字符串中所有的字符变成大写 ?? ??? ?>>>demo1='WWW.BAIDU.COM' ?? ??? ?>>> demo1.lower() ?? ??? ?'www.baidu.com' ?? ??? ?>>> demo1 ?? ??? ?'WWW.BAIDU.COM'
?? ??? ?5.字符串的替换-replace(a,b) a是要替换的原内容 ? b是替换的新内容 ?? ??? ?>>> demo ='www.baidu.com' ?? ??? ?>>> demo.replace('baidu','sina') ?? ??? ?'www.sina.com' ?? ??? ?>>> dmeo
?? ??? ?6.字符串的strip ? 忽略字符串前后空格? ?? ??? ?>>> demo ?? ??? ?'www.baidu.com' ?? ??? ?>>> d =' ? ? ? ? ? ? ? ?sadfadsfd ? ? ? ? ? ? ' ?? ??? ?>>> d ?? ??? ?' ? ? ? ? ? ? ? ?sadfadsfd ? ? ? ? ? ? ' ?? ??? ?>>> d.strip() ?? ??? ?'sadfadsfd' ?? ??? ?>>> d ?? ??? ?' ? ? ? ? ? ? ? ?sadfadsfd ? ? ? ? ? ? '
二、列表(list) 1.列表定义 ?? ?列表是以方括号包围[],元素以逗号分隔,可变,有序,序列之一,python的数据结构之一。 2.列表特点 ?? ?a.有序 ?? ?b.可变(可以对列表进行增删改查) ?? ?c.可以储存不同的数据类型及结构? 3.创建空列表 ?? ?l1=[ ] 4.创建一个有元素列表 ?? ?>>> score = [44,55,89,99,100,85,45,'unkown'] ?? ?>>> score ?? ?[44, 55, 89, 99, 100, 85, 45, 'unkown']
5.列表操作方法 ?? ?增、删、改、访问、弹出、延伸、长度、频次、排序、反转排序 ?? ?5.1向列表内追加元素append() ?默认向后追加 ?? ?>>> score = [44,55,89,99,100,85,45,'unkown'] ?? ?>>> score ?? ?[44, 55, 89, 99, 100, 85, 45, 'unkown'] ?? ?>>> score.append(77) ?? ?>>> score ?? ?[44, 55, 89, 99, 100, 85, 45, 'unkown', 77] ?? ?>>> score.append(77,89) ?? ?Traceback (most recent call last): ?? ? ?File "<stdin>", line 1, in <module> ?? ?TypeError: append() takes exactly one argument (2 given) ?? ?>>> score.append('aaa') ?? ?>>> score ?? ?[44, 55, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa']
?? ?5.1向列表内追加元素insert() ?可以向指定索引位插入元素 ?? ?>>> score ?? ?['www', 44, 55, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa'] ?? ?>>> score.insert(3,'www') ?? ?>>> score ?? ?['www', 44, 55, 'www', 89, 99, 100, 85, 45, 'unkown', 77, 'aaa']
?? ?5.2删除列表内的元素 del? ?? ?>>> del score[0] ?? ?>>> score ?? ?[44, 55, 'www', 89, 99, 100, 85, 45, 'unkown', 77, 'aaa']
?? ?5.3删除列表内的元素 remove ?? ?>>> score=[44, 55, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa'] ?? ?>>> score.append(44) ?? ?>>> score ?? ?[44, 55, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa', 44] ?? ?>>> score.remove(44) ?? ?>>> score ?? ?[55, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa', 44]
?? ?5.4修改列表内的元素 ?? ?>>> score=[44, 55, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa'] ?? ?>>> score[0]=555 ?? ?>>> score ?? ?[555, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa', 44]
?? ?5.5 访问列表内的元素 ?? ?>>> score=[555, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa', 44] ?? ?>>> score[0] ?? ?555 ?? ?>>> score[1:5] ?? ?[89, 99, 100, 85] ?? ?>>> score[::-1] ?? ?[44, 'aaa', 77, 'unkown', 45, 85, 100, 99, 89, 555] ?? ?>>> score[-1] ?? ?44 ?? ?>>> score[0:] ?? ?[555, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa', 44]
?? ?5.6弹出(删除)列表内的元素 ?? ??? ?pop() ? ?默认弹出最后一个元素 并删除 ?? ??? ?pop(1) ?删除索引为1的元素
?? ?>>> score=[555, 89, 99, 100, 85, 45, 'unkown', 77, 'aaa', 44] ?? ?>>> score.pop() ?? ?44 ?? ?>>> score.pop() ?? ?'aaa' ?? ?>>> score.pop() ?? ?77 ?? ?>>> score ?? ?[555, 89, 99, 100, 85, 45, 'unkown'] ?? ?>>> score.pop(1) ?? ?89
?? ?5.7 延伸extend() ?? ??? ?将整个数据结构中的元素拆分追加到原列表中。
?? ?>>> score=[555, 85, 45, 'unkown', 1, 'aa', [1, 2, 3]] ?? ?>>> score ?? ?[555, 85, 45, 'unkown', 1, 'aa', [1, 2, 3]] ?? ?>>> score.extend(['abc','bcd','def']) ?? ?>>> score ?? ?[555, 85, 45, 'unkown', 1, 'aa', [1, 2, 3], 'abc', 'bcd', 'def'] ?? ?>>> score.extend('www') ?? ?>>> score ?? ?[555, 85, 45, 'unkown', 1, 'aa', [1, 2, 3], 'abc', 'bcd', 'def', 'w', 'w', 'w'] ?? ?>>> score.extend([1,2,3,4,4]) ?? ?>>> score ?? ?[555, 85, 45, 'unkown', 1, 'aa', [1, 2, 3], 'abc', 'bcd', 'def', 'w', 'w', 'w', 1, 2, 3, 4, 4] ?? ?>>> ?? ?5.8 ?计算列表内的长度(个数)len函数 ?? ?>>> score=[555, 85, 45, 'unkown', 1, 'aa', [1, 2, 3], 'abc', 'bcd', 'def', 'w', 'w', 'w', 1, 2, 3, 4, 4] ?? ?>>> len(score) ?? ?18 ?? ?5.9 访问列表内某个元素出现的频率count ?? ?>>> score=[555, 85, 45, 'unkown', 1, 'aa', [1, 2, 3], 'abc', 'bcd', 'def', 'w', 'w', 'w', 1, 2, 3, 4, 4] ?? ?>>> len(score) ?? ?18 ?? ?>>> score.count(85) ?? ?1 ?? ? ?? ?6.0正排序 sort() ?? ?>>>score=[123,44,0,67,12.3,'Aaa','aa','B'] ?? ?>>> score.sort() ?? ?>>> score ?? ?[0, 12.3, 44, 67, 123, 'Aaa', 'B', 'aa'] ?? ?>>>
?? ?6.1返排序 ?? ?>>>score=[123,44,0,67,12.3,'Aaa','aa','B'] ?? ?>>> score.reverse() ?? ?>>> score ?? ?['aa', 'B', 'Aaa', 123, 67, 44, 12.3, 0]
?? ?>>>score=[123,44,0,67,12.3,'Aaa','aa','B'] ?? ?>>> score ?? ?[0, 12.3, 44, 67, 123, 'Aaa', 'B', 'aa'] ?? ?>>> ?? ?>>> ?? ?>>> ?? ?>>> score.sort(reverse=True) ?? ?>>> score ?? ?['aa', 'B', 'Aaa', 123, 67, 44, 12.3, 0] ?? ?>>> score.sort(reverse=False) ?? ?>>> score ?? ?[0, 12.3, 44, 67, 123, 'Aaa', 'B', 'aa']
6.其他操作 ?? ?1.列表内元素判断和嵌套取值 ?? ?>>> score=[1,2,3,4,['hello',['www','NBA']]] ?? ?>>> score ?? ?[1, 2, 3, 4, ['hello', ['www', 'NBA']]] ?? ?>>> 1 in score ?? ?True ?? ?>>> 'hello' in score ?? ?False ?? ?>>> 'hello' in score[-1] ?? ?True ?? ?>>> 'www' in score[-1][-1] ?? ?True ?? ?>>> 'www' in score[-1] ?? ?False ?? ?>>> score[-1] ?? ?['hello', ['www', 'NBA']] ?? ?>>> score[-1][-1] ?? ?['www', 'NBA'] ?? ?>>> score[-1][-1][-1] ?? ?'NBA' ?? ?>>> score[-1][-1][0] ?? ?'www' ?? ?>>> score[-1][-1][-1] ?? ?'NBA' ?? ?>>> score[-1][-1][-2] ?? ?'www'
?? ?2.列表之间大小比较(只比较列表内的第一个元素) ?? ?>>> l1=[111,2333,444,666,'aaaa','bcd'] ?? ?>>> l2=[333,454,67,'abcd','nbcbd'] ?? ?>>> l1 > l2 ?? ?False ?? ?>>> l2 < l1 ?? ?False ?? ?>>> l1>l2 ?? ?False
?? ?3.元素移动 ?? ?>>> l1=[111,2333,444,666,'aaaa','bcd'] ?? ?>>> l1[0],l1[1]=l1[1],l1[0] ?? ?>>> l1 ?? ?[2333, 111, 444, 666, 'aaaa', 'bcd']
?? ?4.列表求和 ?? ?>>> l1=[2333, 111, 444, 666] ?? ?>>> sum(l1) ?? ?3554
三、元组 (tuple) 补充:字符串也是数据结构 1.元组的定义:元组是以小括号包围,元素以逗分隔的序列之一。python的数据结构之一。 2.元组特点: ?? ?a.有序 ?? ?b.不可变 ?? ?c.可以存储不同的数据类型及结构? ?? ?d.不可以对元祖内的元素进行删除
3.定义一个空元组 ?? ?>>> demo =() ?? ?>>> type(demo) ?? ?<type 'tuple'> ?? ?>>>
4.访问元组的元素 ?? ?>>> demo =(1,2,3,4,5,6,7,8,9,'a') ?? ?>>> ?? ?>>> demo ?? ?(1, 2, 3, 4, 5, 6, 7, 8, 9, 'a') ?? ?>>> demo[0] ?? ?1 ?? ?>>> demo[0:4] ?? ?(1, 2, 3, 4) ?? ?>>> demo[::] ?? ?(1, 2, 3, 4, 5, 6, 7, 8, 9, 'a') ?? ?>>> demo[::-1] ?? ?('a', 9, 8, 7, 6, 5, 4, 3, 2, 1) ?? ?>>> demo[-1] ?? ?'a'?
5.对整个元祖进行删除 ?? ?>>> demo =(1,2,3,4,5,6,7,8,9,'a') ?? ?>>> del demo ?? ?>>> demo ?? ?Traceback (most recent call last): ?? ? ?File "<stdin>", line 1, in <module> ?? ?NameError: name 'demo' is not defined
6.创建一个元祖,元祖里面只有一个元素的写法: ?? ?需要加逗号,消除歧义。 ?? ?>>> a = (1) ?? ?>>> a ?? ?1 ?? ?>>> type(a) ?? ?<type 'int'> ?? ?>>> a = (1,) ?? ?>>> type(a) ?? ?<type 'tuple'> ?? ?>>>
四、字 ?典(dict) ?? ?1.字典定义?? ? ?? ??? ?字典是以花括号 { }包围,元素以键,值对的形式存在,并且元素之间使用逗号分隔的可变的序列之一。 ?? ??? ?字典是python中唯一一个具有映射关系(比如:通讯录里面联系人和电话)的数据结构。 ?? ?2.字典特点 ?? ??? ?a.无序 ?? ??? ?b.当字典中有重复键产生时,字典会默认保留最后一个键 ?? ??? ?c.字典的键是唯一的,不可变的 ?? ??? ?d.字典的值可以通过键来修改 ?? ?创建一个空字典: ?? ??? ?>>> dic={} ?? ??? ?>>> type(dic) ?? ??? ?<type 'dict'>
?? ?创建一个有键和值得字典: ?? ?>>> dic1={'name':'wanguolin','age':18,'address':'anhui','hobby':'study'} ?? ?>>> dic1 ?? ?{'hobby': 'study', 'age': 18, 'name': 'wanguolin', 'address': 'anhui'}
?? ?当字典中有重复键产生时,字典会默认保留最后一个键。 ?? ?>>> dic1={'name':'wanguolin','age':18,'address':'anhui','hobby':'study','name':'xiewei'} ?? ?>>> dic1 ?? ?{'hobby': 'study', 'age': 18, 'name': 'xiewei', 'address': 'anhui'} ?? ?>>> dic1={'name':'wanguolin','age':18,'address':'anhui','hobby':'study','name':'xiewei'}
?? ?字典的值可以通过键来修改。 ?? ?>>> dic1={'name':'wanguolin','age':18,'address':'anhui','hobby':'study','name':'xiewei'} ?? ?>>> dic1['name']='fuxinggaozhao' ?? ?>>> dic1 ?? ?{'hobby': 'study', 'age': 18, 'name': 'fuxinggaozhao', 'address': 'anhui'}
?? ?字典中删除键,值对应的也会被删除。 ?? ?>>> dic1={'hobby': 'study', 'age': 18, 'name': 'fuxinggaozhao', 'address': 'anhui'} ?? ?>>> del dic1['name'] ?? ?>>> dic1 ?? ?{'hobby': 'study', 'age': 18, 'address': 'anhui'} ?? ?>>>
?? ?3.取所有的键和所有的值 ?? ?.keys() ? ? 取所有的键 ?? ?.values() ?取所有的值 ?? ?>>> dic1={'hobby': 'study', 'age': 18, 'address': 'anhui'} ?? ?>>> ?? ?>>> dic1.keys() ?? ?['hobby', 'age', 'address'] ?? ?>>> ?? ?>>> dic1.values() ?? ?['study', 18, 'anhui']
?? ?字典-----items() 将字典中的键和值同过元组的形式返回,并存储到列表中。 ?? ?>>> dic1={'hobby': 'study', 'age': 18, 'address': 'anhui'} ?? ?>>> ?? ?>>> dic1.items() ?? ?[('hobby', 'study'), ('age', 18), ('address', 'anhui')]
?? ?类似的还有: ?? ?>>> list1=['name','age','address'] ?? ?>>> list2=['zhangshan',25,'shenzhen'] ?? ?>>> demo = zip(list1,list2) ?? ?>>> demo ?? ?[('name', 'zhangshan'), ('age', 25), ('address', 'shenzhen')] ?? ?>>>
?? ?4.判断键是否在字典中 in not in? ?? ?>>> dic1={'hobby': 'study', 'age': 18, 'address': 'anhui'} ?? ?>>> ?? ?>>> ?? ?>>> 'age' in dic1 ?? ?True
?? ?5.字典常用操作函数 ?? ??? ?字典-----get() ? ?? ??? ??? ?1.取键对应的值 ?? ??? ??? ?2.取一个不存在的键,设置默认提示
?? ??? ?>>> dic1={'hobby': 'study', 'age': 18, 'address': 'anhui'} ?? ??? ?>>> dic1.get('hobby') ?? ??? ?'study' ?? ??? ?>>> ?? ??? ?>>> ?? ??? ?>>> dic1 ?? ??? ?{'hobby': 'study', 'age': 18, 'address': 'anhui'} ?? ??? ?>>> dic1.get('name') ?? ??? ?>>> dic1 ?? ??? ?{'hobby': 'study', 'age': 18, 'address': 'anhui'} ?? ??? ?>>> ?? ??? ?>>> ?? ??? ?>>> dic1.get('name','None name!') ?? ??? ?'None name!' ?? ??? ?>>> dic1 ?? ??? ?{'hobby': 'study', 'age': 18, 'address': 'anhui'} ?? ??? ?>>> ?? ??? ?>>> dic1.get('gender','none gender') ?? ??? ?'none gender'
?? ??? ?字典-----pop() 弹出并删除 (需要给出指定的键) ?? ??? ?>>> dic1={'hobby': 'study', 'age': 18, 'address': 'anhui'} ?? ??? ?>>> dic1.pop('age') ?? ??? ?18 ?? ??? ?>>> dic1 ?? ??? ?{'hobby': 'study', 'address': 'anhui'} ?? ??? ?>>> dic1.pop('address','hobby') ?? ??? ?'anhui' ?? ??? ?>>> dic1 ?? ??? ?{'hobby': 'study'}
?? ??? ?字典----和popitem() ?? ??? ?>>> dic1={'name':'zhangshan','address':'beijing','sex':'man'} ?? ??? ?>>> dic1.popitem() ?? ??? ?('sex', 'man') ?? ??? ?>>> ?? ??? ?>>> dic1.popitem() ?? ??? ?('name', 'zhangshan') ?? ??? ?>>> ?? ??? ?>>> dic1 ?? ??? ?{'address': 'beijing'} ?? ??? ?>>> dic1.popitem('address') ?? ??? ?Traceback (most recent call last): ?? ??? ? ?File "<stdin>", line 1, in <module> ?? ??? ?TypeError: popitem() takes no arguments (1 given) ?? ??? ?>>> dic1 ?? ??? ?{'address': 'beijing'} ?? ??? ?>>> dic1.popitem() ?? ??? ?('address', 'beijing') ?? ??? ?>>> dic1 ?? ??? ?{}
?? ??? ?字典-----update() ?? ??? ?>>> dic1={'name':'zhangshan'} ?? ??? ?>>> dic={} ?? ??? ?>>> dic.update(dic1) ?? ??? ?>>> dic ?? ??? ?{'name': 'zhangshan'} ?? ??? ?>>> dic1 ?? ??? ?{'name': 'zhangshan'}
?? ??? ?字典-----setdefault()设置默认? ?? ??? ?1.可以取现有的键对应的值 ?? ??? ?>>> dic1={'home': 'beijing', 'name': 'zhangshan', 'address': None} ?? ??? ?>>> dic1.setdefault('home') ?? ??? ?'beijing' ?? ??? ?>>> dic1.setdefault('address') ?? ??? ?>>> dic1.setdefault('name') ?? ??? ?'zhangshan'
?? ??? ?2.可以向字典中设置新键,键对应的值默认为None ?? ??? ?>>> dic1={'name': 'zhangshan'} ?? ??? ?>>> ?? ??? ?>>> ?? ??? ?>>> dic1.setdefault('address') ?? ??? ?>>> dic1 ?? ??? ?{'name': 'zhangshan', 'address': None} ?? ??? ?>>> dic1.setdefault('address','beijing') ?? ??? ?>>> dic1 ?? ??? ?{'name': 'zhangshan', 'address': None}
?? ??? ?3.可以向字典中设置新建以及对应的值? ?? ??? ?>>>dic1={'name': 'zhangshan', 'address': None} ?? ??? ?>>> dic1.setdefault('home','beijing') ?? ??? ?'beijing' ?? ??? ?>>> dic1 ?? ??? ?{'home': 'beijing', 'name': 'zhangshan', 'address': None}
?? ??? ?字典-----哈希(hash)算法 ?? ??? ??? ?根据键来取值得方式我们称为哈希算法。 ?? ??? ?字典-----列表和字典区别 ?? ?? ??? ??? ?1.字典的查找速度快,占用的内存大。典型的用空间换时间 ?? ??? ??? ?2.列表相对于字典的查找速度慢。 五、Python操作符 ?? ?1.算数运算 ? ? ?? ??? ?+ ?- ?* ?/ (//)除法 ,取商 ? %除法(取余数) ? ?**幂 ?? ?2.比较运算 ?? ??? ?>? ?? ??? ?< ?? ??? ?>= ?? ??? ?<= ?? ??? ?== ?? ??? ?!= (<>) ?? ?3.赋值运算? ?? ??? ?num = 10 ?? ??? ?num+=1 ? ? ? ? ?等价于-------->(num = num + 1) ?? ?4.成员关系 ?? ??? ?in ? 在.....什么里面 ?包含 ?? ??? ?not ?in ? ?不在什么里面 ?不包含?
六、输入和输出 ?? ?print ?输出 ?? ?input: 对输入的数据类型有强校验,比较敏感,输入的数据类型一定是标准的数据类型。 ?? ?raw_input:对输入的数据类型没有强校验。 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ?message ?= input('请输入信息:') ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ?? ?message_ = input('请再次输入信息') ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ?? ?print 'welcome to shenzhen,%s, how are you? %s'%(message,message_)?
七、IF分支语句 1.Python的真假 ?? ?1.任何非零和非空对象都为真 解释为True ?? ?2.数字0、空对象和特殊对象None均为假 解释为False ?? ?3.比较和相等测试会应用到数据结构中 ?? ?4.返回值为True或False
?? ?>>> not 0 ?? ?True ?? ?>>> not {} ?? ?True ?? ?>>> not [] ?? ?True ?? ?>>> not () ?? ?True ?? ?>>> not '' ?? ?True ?? ?>>> not 1 ?? ?False ?? ?>>> not 0 ?? ?True ?? ?>>> not True ?? ?False ?? ?>>> not False ?? ?True
2.组合条件测试 ?? ?X and Y :与运算 ?? ? ? ?X ?or ?Y :或运算 ?? ? ? ? ? not ? ?X :非运算
注意事项: ?? ?1.括号的优先级最高 ?? ?2.and的优先级大于or ?? ?3.and连接的两个条件都为真,才为真 ?? ?4.or 连接的两个条件有一个为真就为真
4.IF语句基本结构: ?? ?if ? 条件: ?? ? ? ? ?if语句块 ?? ?else: ?? ? ? ? ?else语句块
4.1IF语句结合比较运算 ?? ??? ?>? ?? ??? ?< ?? ??? ?>= ?? ??? ?<= ?? ??? ?== ?? ??? ?!= (<>) 注意:python对缩进有严格要求,默认是4个空格。
实例: num = 50 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if num > 50: ? ? ? ? ? ? ? ? ? ? ? ? ?? ? ? print 'num is more than %s'% num ?? else: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print 'num is less than %s'% num ??
结合比较运算: num = 10 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? if num > 50 and (num > 10 or num == 10): ? ? print 'num is more than %s'% num ? ? else: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ? ? print 'num is less than %s'% num ? ? ? ? ? ? ? ? ? ? 包含和不包含的例子:? message = 'welcome to shenzhen' ? ?? if 'we' not in message: ? ? ? ? ? ?? ? ? print 'hello,jim %s'%message ? ? else: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ? ? print 'byebye,jim %s'%message ?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? num = 50 ? ? ? ? ? ? ? ? ? ? ? if num != 50: ? ? ? ? ? ? ? ?? ? ? print 'num is 50' ? ? ? ?? else: ? ? ? ? ? ? ? ? ? ? ? ?? ? ? print 'num is not 50' ? ??
5.IF...ELIF嵌套语句 ?? ?if ? 条件: ?? ? ? ? ?if语句块 ?? ?elif ?条件: ?? ? ? ? ?elif语句块 ?? ?elif ?条件: ?? ? ? ? ?elif语句块 ?? ?else: ?? ? ? ? ?else语句块 实例:
DEFAULT = 50 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? guess_number = int(input('请输入一个数字:')) ? ? ? ? ? ? ? ? ? result_number = DEFAULT ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if guess_number > result_number: ? ? ? ? ? ? ? ? ? ? ?? ? ? print '%s 大于 %s'%(guess_number,result_number) ? ? ? elif guess_number < result_number: ? ? ? ? ? ? ? ? ? ?? ? ? print '%s 小于 %s'%(guess_number,result_number) ? ? ? else: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print '%s 等于 %s'%(guess_number,result_number) ? ? ?
注意事项: 1.else语句表示的是另一种选择 2.elif 和else作为子句不能单独使用,必须和IF ?for ?while结合使用
6.IF嵌套语句 ?? ?if ?条件: ?? ? ? ? if条件: ?? ??? ?if语句块 ?? ? ? ? elif: ?? ? ? ? ? ? ? ? else语句块 ? ? ? ? ? ? ?else: ?? ??? ?else语句块 嵌套实例:?? ??? ? name=raw_input('请输入一个名字:') if name.endswith('guolin'): ? ? if name.startswith('wan'): ? ? ? ? print "hello,%s"%name ? ? elif name.startswith('xie'): ? ? ? ? print 'byebye,%s'%name ? ? elif name.startswith('peng'): ? ? ? ? print 'ni hao shuai %s'%name ? ? else: ? ? ? ? print '-------------------->' else: ? ? print 'game is over++++++++++++++++++++>'
IF和IF语句并列使用: num = 10? if ?num > 5: ? ? print 'num 大于5' if ?num > 50: ? ? print 'num 大于50' elif num < 50: ? ? print 'num 小于50' else: ? ? print '+++++++++++++++++++>'
练习: 小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数: ?? ?低于18.5:过轻 ?? ?18.5-25:正常 ?? ?25-28:过重 ?? ?28-32:肥胖 ?? ?高于32:严重肥胖
七、For循环 1.For循环定义 ?? ?for循环是从后面的序列依次取值赋值给前面的变量,每赋值一次,执行一次语句块的内容,也就是循环一次。
2.For循环结构?? ? ?? ?for ?变量 ?in ? 可迭代的对象(序列): ?? ??? ?语句块?
3.For循环实例遍历(字符串/列表/字典/序列索引迭代) #for循环遍历字符串 for demo in 'Python': ? ? print '当前打印的是',demo
#for循环计数循环 demo = 'hello_world' for index in 'Python': ? ? print '执行一次',demo
#for循环遍历列表 for index in ['python','java','php','C++','ruby','javascript']: ? ? print '当前从列表中取出的值是',index + '它的长度是',len(index)
#for循环遍历字典 dic={'name':"chenglong",'age':250,'address':'beijing'} for key,value in dic.items(): ? ? print key,'<====>',value
#序列索引迭代 list=['apple','orange','pear','banana','mangguo'] for index in range(len(list)): ? ? print '当前打印的是',list[index],'它的长度是',len(list[index])
4.range()和xrange()生成器 ?? ?range生成器一般用于迭代数量较小的场景。 ?? ?>>> range(10) ?? ?[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ?? ?>>> range(1,10) ?? ?[1, 2, 3, 4, 5, 6, 7, 8, 9] ?? ?>>> range(1,10,2) ?? ?[1, 3, 5, 7, 9]
?? ?xrange生成器用于迭代数量较大的场景。 ?? ?>>> xrange(1000) ?? ?xrange(1000)
5.enumerate内置函数(枚举) 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值。 a=[1,2,3,4,5,6,7,8]
list=('apple','orange','pear','banana','mangguo') for index,values in ?enumerate(list): ? ? print index,'==',values
list=('apple','orange','pear','banana','mangguo') for index,values in ?enumerate(list): ? ? print index,'==',values
6.For循环嵌套 ?? ?break:中断循环 ?? ?continue:跳出当前循环?
#二层循环嵌套 for i in range(1,10): ? ? print '--------------->',i ? ? for j in range(1,i+1): ? ? ? ? print '+++++++++++++>',j ? ? ? ? if j == 5: ? ? ? ? ? ? break
for i in range(1,10): ? ? print '--------------->',i ? ? for j in range(1,10): ? ? ? ? print '+++++++++++++>',j ? ? ? ? if j == 5: ? ? ? ? ? ? break
#结合break ?continue for ?i ?in 'python': ? ? if i == 'o': ? ? ? ? continue ? ? else: ? ? ? ? print i
#三层循环嵌套 for i in range(1,5): ? ? print '--------------->',i ? ? for j in range(1,5): ? ? ? ? print '+++++++++++++>',j ? ? ? ? for k in range(1,5): ? ? ? ? ? ? print '================>',k
For循环编程题 ?? ?练习1.计算1-100以内的和. ?? ?练习2.列举1-100以内偶然,将结果存储到列表list1中. ?? ?练习3.使用for循环依次输入三个数,储存到一个列表中,在列表中进行排序. ?? ?练习4.有1、2、3、4个数字,能组成多少个互不相同且无重复数字三位数. ?? ?练习5.使用for循环嵌套实现99乘法表
#1+2+3+4+5+6+..... #0+1 ?1 #0+1+1 ?2 #0+1+1+1 ?3
#练习1.计算1-100以内的和. sum = 0 print sum for i ?in range(1,101): ? ? sum = sum + i print sum
#练习2.列举1-100以内偶然,将结果存储到列表list1中 list2 = [] for ?i in range(2,101,2): ? ? list2.append(i) print list2
list1=[] for ?i ?in range(1,101): ? ? if i % 2 == 0: ? ? ? ? list1.append(i) print list1
#练习3.使用for循环依次输入三个数,储存到一个列表中,在列表中进行排序. l1=[] for ?i ?in '123': ? ? number = int(input("请输入数字:")) ? ? l1.append(number) l1.sort() print l1
# 练习4.有1、2、3、4个数字,能组成多少个互不相同且无重复数字三位数. #range(5) ? 1 2 3 4 for i ?in range(1,5): ? ? for j ?in range(1,5): ? ? ? ? for k in range(1,5): ? ? ? ? ? ? if (i!=k) and (i!=j) and (j!=k): ? ? ? ? ? ? ? ? print i,j,k
#练习5.使用for循环嵌套实现99乘法表 ? 2层嵌套 ''' 1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=9 ''' for ?i ?in range(1,10): ? ? for j in range(1,i+1): ? ? ? ? print "%d*%d=%d"%(i,j,i*j), ? ? print '\n' 0 作业: 练习6.逐一分开显示字典d1中的所有元素,类似如下: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? k1 === v1 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? k2 === v2 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? k3 === v3 ? ? ? ? ? ? ? ? 练习7.逐一显示列表中l1=['Sun','Mon','Tue','web','Fri','Sat']中索引为奇数的元素. 练习8.使用for循环生成1*1,2*2,3*3,4*4 ....10*10的列表list1. 练习9.练习8.将属于列表l1=['Sun','Mon','Tue','web','Fri','Sat'],但不属于列表l2=['Sun','Mon','Tue'的所有元素定义为一个新列表.
八、While循环 1.While循环定义 ?? ?如果顶层测试条件为真,While循环会一直执行隶属于while语句,直到条件为假,退出循环。
2.While循环结构 ?? ?while ?条件: ?? ??? ?while 语句
#死循环实例 while 1: ? ? print '-------------->'
while True: ? ? print '-------------->'
count = 0 while count < 1: ? ? print '++++++++>'
#条件不满足退出循环 count = 0 while count < 5: ? ? print 'this is print number less than %s'%count ? ? count+=1
3.While...else循环结构 count = 0 while count < 5: ? ? print 'this is print number less than %s'%count ? ? count+=1 else: ? ? print 'this is print number more than %s'%count
3.While循环实例 #####实现通过索引打印URL##### URL = 'www.baidu.com' while URL: ? ? print URL ? ? URL = URL[1:]
#####实现过滤器######## #当我们输入 q 或者 out 这个关键字的时候,直接停止循环,否则,就将每次输入的内容追加到列表中 test = [] while True: ? ? content = raw_input('enter your content:') ? ? if content=='q' or content=='out': ? ? ? ? break ? ? else: ? ? ? ? test.append(content) print test
#####实现奇偶分离###### #将list列表中的奇数和偶数分别放到odd ?even 列表 list = [1,2,3,55,6,788,9,90,90,34,56,78] odd=[] even=[] while len(list)>0: ? ? number=list.pop() ? ? if number %2 == 0: ? ? ? ? odd.append(number) ? ? else: ? ? ? ? even.append(number) print even print odd
#####IF嵌套WHILE结合##### DEFAULT = 50 result_number = DEFAULT count = 0 while count < 3: ? ? guess_number = int(input('请输入一个数字:')) ? ? if guess_number > result_number: ? ? ? ? print '%s 大于 %s'%(guess_number,result_number) ? ? elif guess_number == result_number: ? ? ? ? print '%s 等于 %s'%(guess_number,result_number) ? ? ? ? #break ? ? ? ? continue ? ? else: ? ? ? ? print '%s 小于 %s'%(guess_number,result_number) ? ? count = count + 1
else: ? ? print '欢迎下次光临————————————>'
总结while循环和for循环的区别: ?? ?1.for循环只能迭代可迭代的对象 ?比如字符串/列表/元祖/字典 ?? ?2.while循环顶端测试条件为真就会执行while循环体直到条件为假退出循环
5.While循环练习题 1)求100以内的奇数之和 ? 99+97+95+93+92+91......1 2)逐一显示指定列表中的所有元素,如list1=[1,2,3,4,5,6,7,8,9,10] 3)逐一显示指定字典中的所有键,并显示结束后说明总键数 4)创建一个包含了100以内奇数的列表
练习题答案: # 1)求100以内的奇数之和 ? 99+97+95+93+92+91......1 1+3+5 n = 99 sum = 0 while n > 0: ? ? sum = sum + n ? ? n = n - 2 ? ? print sum
start_nu = 0 one_nu = 1 end_nu = 100 while one_nu<end_nu: ? ? start_nu = start_nu + one_nu ? ? one_nu = one_nu + 2 print start_nu
# 2)逐一显示指定列表中的所有元素,如list1=[1,2,3,4,5,6,7,8,9,10] list1=[1,2,3,4,5,6,7,8,9,10] count = 0 while len(list1)>count: ? ? print list1[count] ? ? count = count+1
list1=[1,2,3,4,5,6,7,8,9,10] count = 0 while len(list1)>count: ? ? print list1.pop(count)
# 3)逐一显示指定字典中的所有键,并显示结束后说明总键数 dic={'a':1,'b':2,'c':3} keylist = dic.keys() print keylist while keylist: ? ? print keylist.pop() else: ? ? print len(dic)
dic={'a':1,'b':2,'c':3} keylist = dic.keys() count = 0 while len(keylist)>count: ? ? print keylist[count] ? ? count=count+1 else: ? ? print len(keylist)
#4)创建一个包含了100以内奇数的列表 count = 1 end_num = 100 list_ = [] while count <= end_num: ? ? list_.append(count) ? ? count = count + 2 print list_
九、模 ? 块 1.模块定义 ?? ?在python中,一个.py文件就是一个模块。 2.模块组成 ?? ?a.表达式 ?? ?b.语句(包含表达式) ?? ?c.包和模块(windows下面的文件夹---->包 ? ? 文件夹下面的文件---->模块) ?? ?d.程序
3.使用模块的好处 ?? ?1.写代码不必从0开始 ?? ?2.方便调用 ?? ?3.提高脚本的维护性
4.第三方模块 ?? ?selenium ?库(一个模块) ?? ?BeautifulSoap ? ?爬虫相关 ?? ?urllib2 ? ? ? ? ? ? ? ?和网络相关 ?? ?urllib3 ? ? ? ? ? ? ? ?和网络相关 ?? ?requests ? ? ? ? ? ? 接口测试相关库? ?? ?.......
5.Python模块引用的几种方式 #第一种方式 from ?模块名 ?import 模块名下面的函数或者方法 #ctime:获取系统当前显示的时间 ?sleep:休眠
from ?time import ctime,sleep print ctime() #打印系统当前时间 sleep(5) ? ? ? ?#休眠5S print ctime() #再次打印系统当前时间
#第二种方式from ?模块名 ?import * (* 代表该模块下面的所有的方法或者函数) from ?time import * print ctime() #打印系统当前时间 sleep(5) ? ? ? #休眠5S print ctime() #再次打印系统当前时间
#第三种:import 模块名 ?直接引模块 import ?time #导入时间模块 print time.ctime() time.sleep(5) print time.ctime()
6.练习random模块 ? ? 题目:使用模块引用的三种方式实现生成随机数 ?random.randint(a,b) a是起始数字,b结束数字
九、文件读写 1.open函数(内置函数) ?? ?格式:open(文件路径,'文件的读写方式')
2.读文件方法? ?? ?.read() ? ? ? ? ?没有参数,默认读取文件的全部内容 ? ?? ?.readline() ? ?默认读取首行 ?? ?.readlines() ?默认读取文件所有内容 包含换行符 \n ?? 3.写文件? ?? ?.write() ? ? () ?写入文件的内容? 4.关闭文件? ?? ?.close() ? ? ? ? 用来关闭文件? ?? ?.closed ?? ? ? ? ? ?用来检验文件是否正确关闭 ?
5.读写文件(创建文件)实例 ?? ?#写文件的过程 ?? ??? ?filename = ?open('test.txt','w') ?? ??? ?filename.write('zhangshan,123456\nlishi,555555\nwangwu,22222') ?? ??? ?filename.close()? ?? ??? ?#print filename.closed ?#检查文件是否正确被关闭 ? 返回True
?? ?#读文件的过程 ?? ??? ?file = open('test.txt','r') ?? ??? ?read_type = file.read() ?? ?? ??? ?read_type1 = file.readline() ?? ??? ?read_type2 = file.readlines() ?? ??? ?print read_type2
7.FOR循环读取txt文件?? ? ?? ?file = open('test.txt','r') ?? ?read_type2 = file.readlines() ?? ?for ?read ?in ?read_type2: ?? ? ? ?print read
?? ?运行结果: ?? ?zhangshan,123456
?? ?lishi,555555
?? ?wangwu,22222
8.FOR循环结合split字符串结合文件读写? file = open('test.txt','r') read_type2 = file.readlines() for ?read ?in ?read_type2: ? ? username = read.split(',')[0] ? ? password = read.split(',')[1]
#FOR循环结合自动化测试登录的一个demo套路 ?? ?1.将用户名和密码储存到一个txt文件中 ?? ?2.使用for循环将文件中的用户名和密码读取出来 ?? ?3.输出结果使用字符串中的split分隔函数+索引的方式将用户名和密码拆分成两部分 ?? ?4.将拆分好的用户名和密码作用到自动化测试脚本中?
9.with ?... open ... as 方法读取文件用法
?? ?#写文件 ?? ?with ? open('demo_text.txt','w') ?as ?filename: ?? ? ? ?filename.write('helloworld\n123456')
?? ?#读文件 ?? ?with ? open('demo_text.txt','r') as ?f: ?? ? ? ?f1 = f.read() ?? ? ? ?print f1
十、函 ? 数
函数:可以不严谨的认为是一个(面向过程) 补充:为什么学习函数?使用函数的好处? ?? ? ?? ?a.降低代码的冗余 ?? ?b.使代码结构更加清晰 ?? ?c.提高代码的可维护性
1.函数定义和调用 ?? ?函数的结构: ?? ??? ?定义的函数的关键字:def ?? ??? ?函数命名规范: ?? ??? ??? ?等同于变量的命名规范。 ?? ??? ?函数参数 ?? ??? ??? ?如果定义函数时,有参数,请把参数写在参数括号里,如果没有参数,写空括号。 ?? ??? ??? ?形参:在定义函数时,定义的参数是形参。 ?? ??? ??? ?实参:在调用函数时,调传递的参数称为实参。 ?? ??? ?函数的运行原理: ?? ??? ??? ?由实参传递给形参,然后由形参作用到函数的内部。 ?? ??? ?内容块 ?? ??? ??? ?函数定义完成后,需要调用,才可以运行。调用的格式:函数名 + ( ) ? ? (如果在定义函数时函数有参数,在调用时需要给函数传参)? 函数的实例:?? ? #定义无参数的函数 def say_hello(): ? ? print 'hello,zhangshan!' say_hello()
#定义有参数的函数 def say_hello(name): ? ? print 'hello,%s'%name say_hello('wanguolin')
2.函数划分(一) ?? ?根据 ? ?return 关键字来区别函数类型
?? ??? ?计算型函数 ?? ??? ?返回型函数
?? ?如果函数内部有return关键字,说明是返回型函数,函数是有实际值的。 ?? ?如果函数内部没有return关键字,说明是 计算型的函数,函数是没有实际值的。
def say_hello(name,age): ? ? return 'hello,%s,my age is %s'%(name,age)
print type(say_hello('wanuolin',25)) print say_hello('wanuolin',25)
#######同级目录,模块下的函数的调用######## ?? ?demo.py文件如下代码: ?? ?def fuc(x): ?? ? ? ?if x > 0: ?? ? ? ? ? ?return ?x ?? ? ? ?else: ?? ? ? ? ? ?return ?-x
?? ?def ?add(a,b): ?? ? ? ?return ?a+b ?
?? ?def ?sub(a,b): ?? ? ? ?return ?a-b ?
###########demo1.py文件如下代码############
?? ?from demo import fuc,add,sub
?? ?print fuc(5) ?? ?print add(1,2) ?? ?print sub(1,2)
3.函数的划分(二)
?? ?根据函数的参数划分:
?? ?a.位置参数?? ?(和参数的位置有关,具体看代码)
?? ?def say_hello(name,age): ?? ? ? ?print ?'hello,%s,my age is %s'%(name,age)
?? ?say_hello('zhangshan',18) ?? ?say_hello(18,'zhangshan')
?? ?b.默认参数(定义函数是给正常参数一个默认值,如下age=18)
?? ?场景1: 实参传递给默认参数时,会优先采用实参的值使用。 ?? ?def say_hello(name,age=18,): ?? ? ? ?print ?'hello,%s,my age is %s'%(name,age)
?? ?say_hello('zhangshan') ? ? ? ?#正常输出 ?? ?say_hello('zhangshan',250) ? ?#250参数会覆盖age=18这个默认值参数 ?? ?#say_hello('zhangshan',250,360) ?#报错 传递的参数过多
?? ?场景2 : 默认参数放到正常参数的前面,会报错,一定严格禁止这么写!!!!! ?? ?def say_hello(age=18,name): ?? ? ? ?print ?'hello,%s,my age is %s'%(name,age)
?? ?say_hello('zhangshan') ? ? ? ?#报错
?? ?c.可变参数(接受的参数是可变得,不确定的) ?? ?def ?sum(*number): ?? ? ? ?a = 0 ?? ? ? ?for ?i ?in number: ?? ? ? ? ? ?a = a + i ?? ? ? ?return a
?? ?#场景1:传入的参数是可变得 ?? ?#print sum(1,2,3,4,5,6,7)
?? ?#场景2:如果在传递实参的时候,我们想用一个变量去替换原有的过个值,怎么做呢? 如下: ?? ?extra = [1,2,3,4,5,6,7,8,9,10] ?? ?print sum(*extra)
?? ?d.关键字参数(形参=实参,忽略参数传递顺序) ?? ?def say_hello(name,age,**kw): ?? ? ? ?print 'name is ',name ?? ? ? ?print 'age is',age ?? ? ? ?print '接收的关键字参数是不确定的,多个的关键字参数:',kw
?? ?#场景1:传入的关键字参数是多个的情况: ?? ?#say_hello('zhangshan',150,address='beijing',hobby='play',sex='man')
?? ?#场景2:可以通过一个字典储存关键字参数 ?? ?dic={'address':'beijing','hobby':'study','sex':'man'} ?? ?say_hello('lishi',150,**dic)
?? ?e.组合参数(参数的存放顺序一定严格遵循:正常参数-->默认参数-->可变参数-->关键字参数)
?? ?def ?studentinfo(name,age=18,*args,**kw): ?? ? ? ?print ?'my name is',name ?? ? ? ?print ?'my age is',age ?? ? ? ?print ?'other information is',args ?? ? ? ?print ?'other information is',kw
?? ?studentinfo('zhangshan') ?? ?# studentinfo('zhangshan',250) ?? ?# studentinfo('zhangshan',250,'man') ?? ?# studentinfo('zhangshan',250,'man','play','abc') ?? ?# studentinfo('zhangshan',250,'man',562,address='beijing',tel=123456)
练习: ?? ?1.定义一个函数,计算字符串的长度 ?? ?2.定义一个函数,在本地创建10个不同名字的.txt文件
# 1.定义一个函数,计算字符串的长度 ?函数+for循环计数循环 def jlen(str): ? ? j = 0 ? ? for ?i ?in str: ? ? ? ? j = j + 1 ? ? return ?j
result ?= input('请输入一个字符串:') result_ = jlen(result) print '当前打印的字符串的长度是%s'%result_
#2.定义一个函数,在本地创建10个不同名字的.txt文件 def ?create_txt(): ? ? path = r'E:\\Create_text_demo\\' ?#定义文件所在路径 ? ? for ?text in range(1,11): ? ? ? ? with open(path + str(text) + '.txt','w') as file: ? ? ? ? ? ? file.write(str(text)) create_txt()?
十、异常错误处理 1.什么是异常? ?? ?异常是一个事件。比如程序在运行时可能会发生一些未知的错误,为了将这些错误捕捉且不影响程序的正常运行。 ?? ?程序增加异常判断可以让程序更加健壮、完整。当然,程序中有异常也是每一个程序运行的必要条件。
小场景: ?? ?一个人,大冬天在室外洗冷水澡,他可能会感冒。 ?? ?因此,你为他准备了感冒药、金创药、头疼药......
2.异常的分类:Exception异常类 ? ?BaseException异常类(python2.5后出现的新基类)
3.异常类使用几种方式: 第1种:try except 第2种:try except Exception 第2种:try except BaseException,msg 第4种:try except BaseException,msg else 第5种:try except BaseException,msg finally
第1种:try except (该种用法用于接受错误类型,不会报错,前提是要知道try部分内容的错误类型) ?? ?try: ?? ? ? ?print name ?? ?except NameError: ?? ? ? ?pass ?? ?try: ?? ? ? ?a = 10 ?? ? ? ?b = 0 ?? ? ? ?print a/b ?? ?except ZeroDivisionError: ?? ? ? ?pass ?? ?try: ?? ? ? ?open('abc.txt','r') ?? ?except IOError: ?? ? ? ?pass
第2种:try except BaseException,msg (该种用法,不需要知道try部分的错误类型,使用Exception可以直接将错误信息打印,message为变量。有两种用法,如下:) ?? ?try: ?? ? ? ?open('abc.txt','r') ?? ?except Exception,message: ? ? #逗号分隔 ?? ? ? ?print message
?? ?try: ?? ? ? ?open('abc.txt','r')? ?? ?except Exception as message: ? #as分隔 ?? ? ? ?print message
第4种:try except BaseException,msg else (try代码部分和else代码部分保持一致,如果try中的程序是正常的,那么就会执行else语句中的内容,except语句不会被执行,反之。。。) ?? ?try: ?? ? ? ?name='sdafsdafd' ?? ? ? ?print name ?? ?except Exception,msg: ?? ? ? ?print msg ?? ?else: ?? ? ? ?print 'ending------------->'
第5种:try except BaseException,msg finally (不管try部分的代码是否正常运行,都会运行finally下面的程序) ?? ?try: ?? ? ? ?print name ?? ?except Exception,msg: ?? ? ? ?print msg ?? ?else: ?? ? ? ?print 'ending------------->' ?? ?finally: ?? ? ? ?print 'game over++++++++++++++++++++++++>'
#=====================================Selenium篇章==================================================# 一、Pycharm常用快捷键介绍 ?? ??? ?#coding=utf-8 ?声明中文编码? ?? ??? ?新建文件? ?? ??? ?撤销 ctrl + z ?? ??? ?回退 shift + table? ?? ??? ?注释 ?ctrl +/ ?? ??? ?取消注释 ctrl + / ?? ??? ?替换代码 ? ctrl + r ??
二、Selenium环境搭建过程 ?? ??? ?pip是什么? ?? ??? ??? ?pip 是 python 2.7.5版本自动集成在python中的一个包管理工具。
?? ??? ?1. ?win + r ?---->cmd ---->pip install selenium==2.53.0(如果不跟==号默认安装的是最新版本的selenium 3.6.XXX) ?? ??? ?2. ?pip ?show ?selenium ?(查看selenium安装的信息 包括安装本地的路径、下载的地址等) ?? ??? ?3. ?配置浏览器驱动,我们使用的是chromedriver.exe ? ?? ??? ??? ?注意事项: ?? ??? ??? ??? ?1.谷歌浏览器版本和谷歌浏览器驱动对应关系。 ?? ??? ??? ??? ?chromedriver.exe ---2.3.3 ? ? ----->chrome版本是 63.0 ?? ?? ??? ??? ??? ?2.需要把chromdriver.exe配置到 C:\Python27目录下面? ?? ??? ? ?? ??? ?参考谷歌驱动下载地址: ?? ??? ?http://chromedriver.storage.googleapis.com/index.html ?? ??? ?参考谷歌驱动和谷歌浏览器的版本匹配表; ?? ??? ?chromedriver版本?? ?支持的Chrome版本
?? ??? ??? ?v2.35?? ?v62-64 ?? ??? ??? ?v2.34?? ?v61-63 ?? ??? ??? ?v2.33?? ?v60-62 ?? ??? ??? ?v2.32?? ?v59-61 ?? ??? ??? ?v2.31?? ?v58-60 ?? ??? ??? ?v2.30?? ?v58-60 ?? ??? ??? ?v2.29?? ?v56-58 ?? ??? ??? ?v2.28?? ?v55-57 ?? ??? ??? ?v2.27?? ?v54-56 ?? ??? ??? ?v2.26?? ?v53-55 ?? ??? ??? ?v2.25?? ?v53-55 ?? ??? ??? ?v2.24?? ?v52-54
?? ??? ?4. 验证selenium环境是否安装成功,写以下代码,运行无报错说明搭建成功! ?? ??? ?from selenium import ?webdriver ?? ??? ?import ?time? ?? ??? ?driver = ?webdriver.Chrome() ?? ??? ?driver.get('http://www.baidu.com') ?? ??? ?time.sleep(3) ?? ??? ?driver.quit()
三、前端技术 ?? ?HTML ? 静态网页 ?? ?CSS ? ? ? 层叠样式表 ?? ?JAVASCRIPT ? 轻量级的脚本语言
selenium = 人?
?? ?HTML的结构、标签、元素、属性、属性值
?? ?常用的标签 ?? ??? ?<html> ? 声明html文档 ?? ??? ?<body> ?html的身体 ?? ??? ?<p> ? ? ? ? 段落? ?? ??? ?<a> ? ? ? ? 超链接 ?? ??? ?<title> ? ?窗口标题? ?? ??? ?<input> ?文本框 (搜索框) ?? ??? ?<form> ? 表单(一般包括登录用户名文本框、密码文本框、登录按钮) ?? ??? ?<div> ? ? ?块级元素、一个可以包含任意标签的容器? ?? ??? ?<span> ? 块级元素、一个可以包含任意标签的容器、一般用于文本容器? ?? ??? ?<img> ? ? 图像 ?? ??? ?<script> ?js脚本 ?? ??? ?<iframe> 内联框架
?? ?www.w3cschool.com ?万维网?
?? ?HTML的层级关系 ?? ?爷爷类标标签 ---> 父类标签 --->子类标签 ??
?? ?<span class="bg s_ipt_wr" id="s_ipt_wr"><input id="kw" name="wd" class="s_ipt" value="" maxlength="100" autocomplete="off"></span> ?? ?元素解析:
?? ?<span ? ?开始标签(开口标签) ?? ?</span> 结束标签(闭合标签) ?? ?注意:标签一般来讲都是成对出现。
?? ?什么是元素? ? ?? ?在html页面中开始标签和结束标签之间的代码,称为~元素 ?? ?什么是属性? ?? ??? ?<input id="kw" name="wd" class="s_ipt" value="" maxlength="100" autocomplete="off"> ?? ? ?? ?比如: ? id = 'kw' ?? ??? ?id是属性 ?? ??? ?kw是属性对应的属性值
?? ?在定位元素时,一定要保证元素属性值的唯一性。不然在自动化测试元素定位的时候会报错! ?? ? ?? ?验证唯一性的方式: ?? ??? ?鼠标带点击到html页面-->ctrl + f-->找到最下面的搜索框--输入要查找的哪个元素的属性值-->如果html页面上只有一个,说明该属性值可以使用。
四、Webdriver ?API ?
什么是webdriver API? ?? ?它是一套操作浏览器的规范。可以理解为一套N多个函数来实现操作浏览器的方法的集合。 ?? ?比如:元素定位/操作浏览器 /最大化窗口/设置等待/多窗口切换/切换框架/操作警告框等等?
webdriver 提供的元素八大定位:
?? ?id ? ? ? ? ? ? ? ? ? ? ? ? ? ===========>通过id定位 ?? ?name ? ? ? ? ? ? ? ? ? ? ===========>通过name定位 ?? ?class_name ? ? ? ? ? ?===========>通过class定位 ?? ?link_text ? ? ? ? ? ? ? ? ===========>通过文本链接定位 ?? ?partial_link_text ? ? ===========>通过部分文本链接定位 ?? ?tag ? ? ? ? ? ? ? ? ? ? ? ? ===========>通过标签名定位 ?? ?xpath ? ? ? ? ??? ? ? ? ===========>通过xpath语法定位 ?? ?css_selector ? ? ? ? ? ===========>通过CSS选择器语法定位
在Python语言中对应的定位的语法:
?? ?.find_element_by_id('id的属性值') ? ? ? ? ? ? ? ? ? ? ? ? ? 通过id定位?? ? ? ? ? ? (掌握) ?? ?.find_element_by_name('name的属性值') ? ? ? ? ? ? ? 通过name定位 ? ? ? ? (掌握) ?? ?.find_element_by_class_name('class的属性值') ? ? ? 通过class定位 ? ? ? ? ?(掌握) ?? ?.find_element_by_link_text('文本链接') ? ? ? ? ? ? ? ? ? ? ? 通过文本链接定位 ? ? (掌握) ?? ?.find_element_by_partial_link_text('部分文本链接') ? ? 通过部分链接定位 ? ? (链接) ?? ?.find_element_by_xpath('xpath的语法') ? ?? ? ? 通过xpath语法定位 ? (超级重点) ?? ?.find_element_by_csss_selector('css选择器') ? ? ? ? ?通过CSS选择器定位 ? (超级重点)
元素定位的演示:?? ? ?? ??? ?定位前需要了解的几个函数 ?? ??? ??? ?.click() ? ? ? ? ? ? 模拟用户点击事件 ?? ??? ??? ?.send_keys() ? ?模拟用户向文本框输入内容
?? ? ? ? ? ? ? 1. 通过id定位百度的文本框? ?? ? ? ? ? ? ? baidu.find_element_by_id('kw').send_keys(u'土里土气') ? #定位百度文本框,向文本框输入内容 ? ? ? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ? ? ? ? 2.通过name定位百度的文本框? ? ? ? ? ? ? ? ? ? ? ? ? baidu.find_element_by_name('wd').send_keys(123) ? ?
? ? ? ? ? ? ? ? ? ? ? ? 3.通过classs_name定位百度的文本框? ? ? ? ? ? ? ? ? ? ? ? ? baidu.find_element_by_class_name('s_ipt').send_keys(123)
? ? ? ? ? ? ? ? ? ? ? ? 4.通过link_text定位新闻超链接 ?? ? ? ? ? ? ? baidu.find_element_by_link_text(u'hao123').click() ? ? ? ? ?#点击新闻按钮
?? ? ? ? ? ? ? 5.通过partial_link_text定位新闻超链接 ?? ? ? ? ? ? ? baidu.find_element_by_partial_link_text(u'新').click() ? ? ? #点击新闻按钮
############元素定位界的神器 ---- ?倚天剑 ? xpath 定位################################ ?? ? ?? ?xpath的优缺点: ?? ? ?? ??? ?优点: ?? ? ?? ??? ??? ?1.语法丰富 ?? ? ?? ??? ??? ?2.可以通过HTML路径定位? ?? ? ?? ??? ?缺点: ?? ? ?? ??? ??? ?1.抗变性弱 ?? ? ?? ??? ??? ?2.定位不稳定(相对于css定位)
?? ? ?? ?xpath的层级关系表示:?? ? ?/?
?? ?补充:前端工具的安装 ?? ??? ?目的:方便web页面的元素定位。 ?? ??? ?只有火狐浏览器提供。高版本的火狐浏览器没有,只有低版本的有这个插件。 ?? ??? ?FireBug:附加组件--扩展--搜索firebug--点击安装--重启---F12查看 小虫子 ?? ??? ?FirePath:附加组件--扩展--搜索firepath--点击安装--重启---F12查看 小虫子上面有没有firepath
?? ? ?? ?1.xpath的绝对路径定位(使用火狐浏览器寻找元素的xpath的绝对路径) 这种方式有的时候不稳定? ?? ? ?? ?baidu.find_element_by_xpath('html/body/div[1]/div[1]/div/div[1]/div/form/span[1]/input')
?? ? ?? ?2.xpath的属性定位方式(使用频率高一些) ?? ? ?? ?*号代表的是全文搜索 查找慢一些
?? ??? ?baidu.find_element_by_xpath("//input[@name='wd']").send_keys('123') ? #定位百度文本框,向文本框输入内容 ? ? ? ? ? ?? ?? ??? ?baidu.find_element_by_xpath("//*[@name='wd']").send_keys('123') ? #定位百度文本框,向文本框输入内容 ? ? ? ? ? ? ? ? ? ? ?? ?? ? ?? ?3.xpath的父类和属性层级定位 ?? ? ?? ?#bg s_ipt_wr ?当class的属性值带空格的情况下 取class的属性值中的某一个去试 ?? ??? ?baidu.find_element_by_xpath("//span[@class='bg s_ipt_wr']/input").send_keys('123')
?? ? ?? ?4.xpath的爷爷类和属性层级定位 ?? ? ?? ?baidu.find_element_by_xpath("//form[@id='form']/span/input").send_keys('123') ?? ? ?? ?解析: ?? ? ?? ?//form[@id='form'] ?爷爷类的属性和属性值? ?? ? ?? ?/span/input ? ? ? ? ? ? ? 要定位的子类元素
?? ? ?? ?5.xpath的逻辑运算符定位? ?? ? ?? ?baidu.find_element_by_xpath("//input[@name='wd' and @autocomplete='off' ]").send_keys('123') ?? ? ?? ?[@name='wd' and @autocomplete='off' ] ? 使用name和其他属性autocomplete加强元素的唯一性
xpath定位练习: ?? ?1.注册一个sina邮箱 ?http://mail.sina.com.cn/# ?? ?2.实现一个登陆的过程 ?? ??? ?A.获取URL ?? ??? ?B.定位账号文本框 ?? ??? ?C.定位密码文本框 ?? ??? ?D.定位登陆按钮
############元素定位界的神器 ---- 屠龙刀 ? CSS 定位################################?? ? ?? ? ?? ?CSS定位的优缺点: ?? ??? ?优点: ?? ??? ??? ?1.定位速度快 ?? ??? ??? ?2.抗变性强 ?? ??? ??? ?3.语法简洁 ?? ??? ?缺点: ?? ??? ??? ?1.暂时没发现
?? ?CSS的层级关系表示方法: ? ? ?>
?? ?CSS的简写语法: ?? ??? ?id ? ? ? ? ? ? ? ?=================> ? ?# ?? ??? ?class ? ? ? ? ? =================> ? ?. ? ?
?? ??? ?1.根据CSS自有属性id / class 定位? ?? ??? ?baidu.find_element_by_css_selector('#kw').send_keys(123) ? #----- id 定位 ?? ??? ?baidu.find_element_by_css_selector('.s_ipt').send_keys(123) ?#----class 定位
?? ??? ?2.根据CSS的属性定位(最常用) ?? ??? ?baidu.find_element_by_css_selector('input[class="s_ipt"]').send_keys(123)?
?? ??? ?3.CSS的父类和属性层级定位 ?? ??? ?baidu.find_element_by_css_selector('span#s_ipt_wr>input').send_keys(123) ??
?? ??? ?4.CSS的爷爷类标签和属性层级定位 ?? ??? ?baidu.find_element_by_css_selector('form#form>span>input').send_keys(123)?
CSS定位练习: ?? ?1.注册一个sina邮箱 ?http://mail.sina.com.cn/# ?? ?2.实现一个登陆的过程 ?? ??? ?A.获取URL ?? ??? ?B.定位账号文本框 ?? ??? ?C.定位密码文本框 ?? ??? ?D.定位登陆按钮
五、Webdriver应用场景 1.控制浏览器 ?? ?.maximize_window() ? ? ? ? 最大化浏览器窗口 ?? ?.set_window_size(a,b) ? ? ? a、b代表的浏览器的长宽 ?? ?.forword()?? ? ? ? ? ? ? ? ? ?前进操作 ?? ?.back() ? ? ? ? ? ? ? ? ? ? ? ?? ? ? 后退操作 ?? ?.refresh() ? ? ? ? ? ? ? ? ? ? ? ? ? 模拟F5刷新 代码示例:
?? ?from selenium import webdriver ? #导包 ?? ?from time import ?sleep ?? ?baidu = webdriver.Chrome() ? #获取谷歌浏览器的驱动 ?? ?URL ? = 'http://www.baidu.com' ?? ?baidu.get(URL) ? ? #得到百度的URL地址 ?? ?sleep(3) ?? ?baidu.maximize_window() ?#最大化 ?? ?baidu.find_element_by_link_text('新闻').click() ?? ?sleep(3) ?? ?baidu.back() ?#返回到百度首页 ?? ?print baidu.current_url ? ?#获取当前的URL ?? ?sleep(3) ?? ?baidu.forward() #前进到新闻页面 ?? ?print baidu.current_url ?#获取新闻页面的URL ?? ?sleep(3) ?? ?baidu.set_window_size(900,900) ?? ?sleep(3) ?? ?baidu.quit() ?#关闭浏览器
2.webdriver 常用操作方法 ?? ?.click() ? ? ? ? ? ? 点击事件 ? ? ? ?? ?.send_keys() ? ?向文本框输入内容 ?? ?.quit() ? ? ? ? ? ? ?关闭所有浏览器窗口 ?? ?.close() ? ? ? ? ? ?只关闭当前窗口 ?? ?.clear() ? ? ? ? ? ? 清空
3.webdriver常用接口方法 ?? ?.text ? ? ? ? ? ? ? ? ? 获取元素对应文本 ?? ?.is_displayed() ?检查元素是否用户可见
#########获取元素对应的文本########### ?? ?from selenium import webdriver ? #导包
?? ?baidu = webdriver.Chrome() ? #获取谷歌浏览器的驱动 ?? ?URL ? = 'http://www.baidu.com' ?? ?baidu.get(URL) ? ? #得到百度的URL地址 ?? ?sleep(3) ?? ?baidu.maximize_window() ?#最大化 ?? ?result = baidu.find_element_by_id('cp').text ?? ?print result
#########检查元素是否用户可见########### ?? ?from selenium import webdriver ? #导包
?? ?baidu = webdriver.Chrome() ? #获取谷歌浏览器的驱动 ?? ?URL ? = 'http://www.baidu.com' ?? ?baidu.get(URL) ? ? #得到百度的URL地址 ?? ?sleep(3) ?? ?baidu.maximize_window() ?#最大化
?? ?#科学的检查元素是否真正可见 ? True ?False ?? ?result = baidu.find_element_by_id('kw').is_displayed() ?? ?print result
4.webdriver 验证信息的几种方式 ?? ? ?? ?.text ? 获取元素对应的文本 ?? ?.url ? ? 获取当前窗口的URL ?? ?.title ? 获取当前窗口的标题?
代码的实例: ?? ?#使用文本做登录成功后的验证信息 ?? ?login_ok_text = driver.find_element_by_class_name('nick').text ?? ?if login_ok_text == 'luruifengx@sohu.com': ?? ? ? ?print 'pass!' ?? ?else: ?? ? ? ?print 'error!'
?? ?#使用URL做登录成功后的验证信息 ?? ?login_ok_url = driver.current_url ?? ?if ?login_ok_url ?== 'https://passport.sohu.com/mypassport/index': ?? ? ? ?print 'pass!' ?? ?else: ?? ? ? ?print 'error!'
?? ?#验证信息前的思考准备工作: ?? ? ? ?#1.sleep()引入时间 ?? ? ? ?#2.你直接print 驱动获取的title ?url ? text
?? ?#使用窗口的标题 ?? ?login_ok_title = driver.title ?? ?if ?login_ok_title ?== u'我的通行证': ?? ? ? ?print 'pass!' ?? ?else: ?? ? ? ?print 'error!'
##############使用in ?not in ?来判断############ ?? ?from ?selenium import ?webdriver ?? ?import ?time ?? ?DEFAULT = 'luruifengx'
?? ?driver=webdriver.Chrome() ?? ?driver.get("https://passport.sohu.com/") ?? ?driver.find_element_by_name("userid").send_keys("luruifengx@sohu.com") ?? ?driver.find_element_by_name("password").send_keys("qq123456") ?? ?time.sleep(2) ?? ?driver.find_element_by_css_selector("a[class='btn btn-large btn-yellow pull-left']").click() ?? ?time.sleep(5)
?? ?#使用文本做登录成功后的验证信息 ?? ?login_ok_text = driver.find_element_by_class_name('nick').text ?? ?if ?DEFAULT ?in ?login_ok_text: ?? ? ? ?print 'pass!' ?? ?else: ?? ? ? ?print 'error!'
5.设置元素等待 ?? ?sleep(10) ? ? ? ? ? ? ? ? ? Python的time模块提供的方法 ? 强制等待 ?? ?.implicitly_wait(60) ? ?是webdriver提供的隐式等待 (比较温柔,这个用法和网络环境有关系,比较智能一些对比强制等待 ?? ?原理是:在规定时间内比如设置60S,那么假如在运行第10S元素访问到了则会继续往下执行脚本,否则将以轮询的方式不断的去判断元素是否被加载出来)
6.上传文件 ?? ?webdriver中的send_keys()支持上传文件 ?? ?该操作只能针对的是标签 ?input 标签 ? 使用方法:send_keys('上传本地文件的路径')
?? ?上传的实例: ?? ?driver.find_element_by_name("file").send_keys("上传本地文件所在路径")
7.JS操作浏览器滚动条 ?? ?调用js代码实现 ?? ?excute_script("window.scrollTo(0,2500);") ? ? 从最顶端拉到最下面(实际项目中最常用) ?? ?2500为一般参考值,具体要看需求,有的可能1000就到滚动条的底部
代码实例: ?? ?from selenium import webdriver ? #导包
?? ?baidu = webdriver.Chrome() ? #获取谷歌浏览器的驱动 ?? ?URL ? = 'http://www.baidu.com' ?? ?baidu.get(URL) ? ? #得到百度的URL地址 ?? ?sleep(2) ? ? #强制等待 10s ?? ?baidu.maximize_window() ?#最大化 ?? ?baidu.find_element_by_id('kw').send_keys(123) ?? ?baidu.find_element_by_id('su').click()
?? ?#上下拖动 ?? ?baidu.execute_script('window.scrollTo(0,3000);') ?#0-3000 ?从上往下拖动 ?? ?sleep(5) ?? ?baidu.execute_script('window.scrollTo(3000,0);') ?#3000-0 ?从上往下拖动
?? ?#从左往右 需要设置一下长宽 ? 横向阶段 ?? ?sleep(3) ?? ?baidu.set_window_size(400,400) ?? ?sleep(3) ?? ?baidu.execute_script('window.scrollTo(2500,0);') ?#应该是从左往右了 ?? ?sleep(3) ?? ?baidu.execute_script('window.scrollTo(0,2500);') ?#应该是从左往右了
?? ?#同步进行 ?? ?sleep(3) ?? ?baidu.execute_script('window.scrollTo(800,800);') ?
8.多窗口切换 ? ?? ?from selenium import webdriver ?? ? ?? ?baidu = webdriver.Chrome() ? #获取谷歌浏览器的驱动 ?? ?URL ? = 'http://www.baidu.com' ?? ?baidu.get(URL) ? ? #得到百度的URL地址 ?? ?sleep(2) ? ? ? ? ? #强制等待 2s ?? ?baidu.maximize_window() ?#最大化 ?? ?baidu.find_element_by_id('kw').send_keys(u'渗透吧') ?? ?baidu.find_element_by_id('su').click() ?? ?baidu.find_element_by_xpath('//*[@id="1"]/h3/a').click() ?? ?print '点击进入贴吧------------->'
?? ?baidu.switch_to.window(baidu.window_handles[1]) ? ?#切换到第二个窗口
?? ?baidu.find_element_by_link_text(u'进入贴吧').click() ?? ?print '点击结束------------->'
?? ?解析: ?? ?baidu.switch_to.window(baidu.window_handles[1]) ? ?#切换到第二个窗口
?? ?.switch_to.window ? ? ? ? ? ?#切换窗口的函数(方法) ?? ?(baidu.window_handles[1]) ? ?切换到第二个窗口? ?? ?对比python的索引?
?? ?[1] ? ? 代表的是 切换到第二个窗口 ?? ?[2] ? ? 代表的是 切换到第三个窗口
9.下拉框处理 ?? ?三种方式: ?? ?1.引用一个Select类? ?? ?from selenium.webdriver.support.select import ?Select ? 导入 Select 类
?? ?Select(select_demo).select_by_index(1) ? ?#通过索引值 ? ?? ?Select(select_demo).select_by_value('3') ? #通过vale的属性值 ?? ?? ?Select(select_demo).select_by_visible_text(u'审核不通过') ? #通过标签之间的文本描述?
?? ?2.分两步定位(1,先定位下拉框 ?2.操作下拉框里面的值) ?? ?select_demo = driver.find_element_by_id('status') ?#定位下拉框 ?? ?select_demo.find_element_by_css_selector('option[value="1"]').click() ?#操作里面的选项 ?? ?? ?? ?3.一步到位 ?? ?driver.find_element_by_id('status').find_element_by_css_selector('option[value="1"]').click() ?#操作里面的选项 ?? ?driver.find_element_by_id('status') ? ? ?#定位下拉框 ? ?? ?find_element_by_css_selector('option[value="1"]').click() ?#操作下拉框里面的选项 ??
10.警告框处理? ?? ?有三种表现形式: ?? ??? ?1.alert ? ? ? ? ? ? ? 只有一个确定按钮 ?? ?? ??? ?2.confirm ? ? ? ? ?有一个确定按钮和一个取消按钮 ?? ??? ?3.prompt() ? ? ? ?有一个确定按钮和一个取消按钮,还有一个文本框
?? ?以上三种(统一)的定位方式如下: ?? ??? ?句柄.switch_to.alert.accept( ) ? ? 接收弹窗 ?? ??? ?句柄.switch_to.alert.dismiss( ) ? ?拒绝弹窗
11.多框架(iframe)处理? ?? ?框架分为两种:? ?? ??? ?1.平行框架 ? ?? ??? ?2.嵌套框架
?? ?a.当iframe标签本身有id、name属性时的定位策略
?? ??? ?.switch_to.frame('id或者name的属性值')
?? ?b.当iframe标签本身没有id、name属性时的定位策略 ?? ??? ? ?? ??? ?第一步:先用xpath定位到iframe标签,将结果赋值给一个变量 ?? ??? ?第二步:句柄.switch_to.frime(变量)
?? ??? ?demo ?= driver.find_element_by_xpath('//*[@id="f1"]') ?? ??? ?driver.switch_to.frame(demo)
?? ??? ?demo ?= driver.find_element_by_xpath('//*[@id="f2"]') ?? ??? ?driver.switch_to.frame(demo) ?? ??? ??? ? ?? ?c.框架iframe有进入就要有退出,针对的是平行框架 ?? ??? ?.switch_to.default_content() ??
12.键盘事件? ?? ?from selenium import webdriver ?? ?#引入 Keys 模块 ?? ?from selenium.webdriver.common.keys import Keys ?#键盘类 ? ?? ?from time ?import ?sleep
?? ?driver = webdriver.Chrome() ?? ?driver.get("http://www.baidu.com") ?? ?#输入框输入内容 ?? ?driver.find_element_by_id("kw").send_keys('NBA') ?? ?sleep(5)
?? ?#删除多输入的一个 A ?? ?driver.find_element_by_id("kw").send_keys(Keys.BACK_SPACE) ?? ?sleep(3) ?? ?#输# 入空格键+“教程” ?? ?driver.find_element_by_id("kw").send_keys(Keys.SPACE) ?? ?driver.find_element_by_id("kw").send_keys(u"教程") ?? ?sleep(3) ?? ?#ctrl+a 全选输入框内容 ?? ?driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'a') ?? ?sleep(3) ?? ?#ctrl+x 剪切输入框内容 ?? ?driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'x') ?? ?sleep(3) ?? ?#ctrl+v 粘贴内容到输入框 ?? ?driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'v') ?? ?sleep(3) ?? ?#通过回车键盘来代替点击操作 ?? ?driver.find_element_by_id("su").send_keys(Keys.ENTER) ?? ?sleep(3) ?? ?driver.quit()
作业: ?? ?1.自动化测试脚本---实现QQ登录,发送一封有内容的邮件给你同桌 ?? ?2.针对问题1:继续思考一下,怎么实现给多个人发送?(提示:使用字符串的 ?join()方法)? ?? ?3.自动化测试脚本---使用For循环实现百度搜索关键字 ? ?? ?join实例: ?? ?url = 'www.baidu.com' ?? ?':',join(url)
B2C电商项目实战: ?? ?你需要按照以下要求完成实战前的工作准备: ?? ??? ?1.创建11个.py文件,每一个.py文件的命名要参考PPT上给出的命名 ?? ??? ?2.注意:每一个.py文件只写一条测试用例 ?? ??? ?3.注意:每一个.py文件第一行代码 #coding=utf-8 ? ?? ??? ?4.注意:每一个用例的断言应该怎么去写判断( 是用text还是title还是url呢?) ?? ??? ?5.每行代码要写明注释 ?? ??? ?4.如何写自动化测试用例的断言,不清楚的随时问我 ?? ??? ?5.自动化测试用例完成时间截止日期为2018年1月日29日
五、类的概念 ?? ?类(面向对象): ?? ??? ?C++ ? JAVA ?Python ?PHP
?? ?面向对象的编程语言的三大特点: ?? ??? ??? ??? ?1.继承 ?? ??? ??? ??? ?2.封装 ?? ??? ??? ??? ?3.多态 ?? ?函数(面向过程)
?? ?类的定义:类是一个具有相同属性或者方法的集合。 ?? ?类的调用: ?? ??? ??? ?1.定义类的关键字是class ?类的关键字后面跟的是类名(类名的首字母一般是大写) ?? ??? ??? ?2.类名的命名规则和函数的命名规范是一致的 ?? ??? ??? ?3.类下面的函数,叫类方法,类方法中的第一个参数是self,self代表的是类本身的属性 ?? ??? ??? ?必须放在第一个位置,调用类方法时,可以不用传参。 ?? ??? ??? ?4.调用类下面的类方法:类名().类方法()?? ?? ?? ??? ??? ?5. __init__方法用于类的初始化,里面可以绑定一些实例的属性 ?? ? ?? ?代码示例:
?? ??? ?#1.类的定义:类是一个具有相同属性或者方法的集合。 ?? ??? ?#定义一个学生类,给学生类强制绑定一些属性 ?? ??? ?# class Student(): ?? ??? ?# class Student(object): ?? ??? ?# class Student:
?? ??? ?# class Student(): ?? ??? ?# ? ? pass ?? ??? ?# ?? ??? ?# demo = Student() ?#demo是由Student类实例化的一个对象 ?? ??? ?# print demo ?? ??? ?# demo.name = 'zhangshan' ?? ??? ?# print demo.name
?? ??? ?#2.定义一个计算类,实现加减乘除 ?? ??? ?# class Jisuan(): ?? ??? ?# ? ? def add(self,a,b): ? ?#def ?类方法 ? 第一个参数必须是self ? self必须要要写 ?造 ?? ??? ?# ? ? ? ? return a+b ?? ??? ?# ? ? def sub(self,a,b): ?? ??? ?# ? ? ? ? return a-b ?? ??? ?# ? ? def ?multi(self,a,b): ?? ??? ?# ? ? ? ? return ?a*b ?? ??? ?# ? ? def divide(self,a,b): ?? ??? ?# ? ? ? ? return a/b ?? ??? ?# ?? ??? ?# if ?__name__ == "__main__": ?? ??? ?# ? ? demo ?= Jisuan() ?? ??? ?# ? ? print demo.divide(10,3) ?? ??? ?# ? ? print demo.add(1,2) ?? ??? ?# ? ? print demo.multi(10,6)
?? ??? ?# if __name__ == '__main__': ? #运行整个模块的主函数 python的一个内置的函数
?? ??? ?#3.在定义类时,给类强制性的绑定属性 ?__init__ ?? ??? ?# ?? ??? ?# class Student(): ?? ??? ?# ? ? pass ?? ??? ?# ?? ??? ?# B = Student()
?? ??? ?# class Student(): ?? ??? ?# ? ? def __init__(self,name,age): ?? ??? ?# ? ? ? ? self.name = name ?? ??? ?# ? ? ? ? self.age ?= age ?? ??? ?# ?? ??? ?# A = Student('wanguolin',18) ?? ??? ?# print A.name ?? ??? ?# print A.age
?? ??? ?#4.面向过程和面向对象在实现一个打印学生成绩功能上面的区别
?? ??? ?#面向过程 ?? ??? ?# std1={'name':'wanguolin','oracle_score':50} ?? ??? ?# std2={'name':'xiewei','oracle_score':80} ?? ??? ?# ?? ??? ?# def print_score(std): ?? ??? ?# ? ? print "my name is %s,my oracle score is %s"%(std['name'],std['oracle_score']) ?? ??? ?# ?? ??? ?# print_score(std1) ?? ??? ?# print_score(std2)
?? ??? ?#面向对象 ?? ??? ?# class Student(): ?? ??? ?# ? ? def __init__(self,name,oracle_score): ?? ??? ?# ? ? ? ? self.name = name ?? ??? ?# ? ? ? ? self.oracle_score = oracle_score ?? ??? ?# ?? ??? ?# ? ? def print_score(self): ?? ??? ?# ? ? ? ? print 'my name is %s,my oracle score is %s'%(self.name,self.oracle_score) ?? ??? ?# ?? ??? ?# if __name__=='__main__': ?? ??? ?# ? ? Wan = Student('wanguolin',50) ?? ??? ?# ? ? Wan.print_score() ?? ??? ?# ? ? Xie = Student('xiewei',88) ?? ??? ?# ? ? Xie.print_score()
?? ??? ?#类的继承 ?? ??? ?# class ?Animals(): ? #父类 ?? ??? ?# ? ? def ?running(self): ?? ??? ?# ? ? ? ? print 'animals is running------------------>' ?? ??? ?# ?? ??? ?# class Dog(Animals): ?? ??? ?# ? ? def singing(self): ?? ??? ?# ? ? ? ? print 'dog is singing=====================>' ?? ??? ?# ?? ??? ?# demo = Dog() ?? ??? ?# demo.running() ?? ??? ?# demo.singing()
?? ??? ?#多态的一个例子:子类和父类有共同的方法时,优先 使用子类的方法 ?? ??? ?# class ?Animals(): ? #父类 ?? ??? ?# ? ? def ?running(self): ?? ??? ?# ? ? ? ? print 'animals is running------------------>' ?? ??? ?# ? ? ? ?? ?? ??? ?# class Dog(Animals): ?? ??? ?# ? ? def running(self): ?? ??? ?# ? ? ? ? print 'dog is singing=====================>' ?? ??? ?#? ?? ??? ?# demo = Dog() ?? ??? ?# demo.running()
六、unittest单元测试框架:
?? ?Python: ?unittest(Pyunit )框架 、pytest框架 ?? ?JAVA: ? ? Junit ?TestNg ?? ?PHP: ? ? ? larverl框架?
1.为什么要使用单元测试框架(framework) ? ? 为了解决某一类问题,而设计出来的工具。
? ? ?? ?现状: ? ? ?? ??? ?a.线性脚本、 ? ? ?? ??? ?b.当测试用例达到量级,没有代码的组织管理、 ? ? ?? ??? ?c.测试用例达到成百上千条的时侯、维护困难、 ? ? ?? ??? ?d.没有日志 用例总数、通过数、失败数量、环境信息、 ? ? ?? ??? ?e.没有丰富的断言方法 、
? ? ?? ?解决现状: ? ? ?? ?引入unittest单元测试框架,解决现状。 ? ? ?? ??? ?a.测试用例达到量级时,通过unittest单元测试框架可以解决 ? ? ?? ??? ?b.提供了丰富的断言方法: ? ? ?? ??? ??? ?assertEqual(a,b,[msg='测试失败时打印的信息']):断言a和b是否相等,相等则测试用例通过。 ?? ??? ??? ?assertNotEqual(a,b,[msg='测试失败时打印的信息']):断言a和b是否相等,不相等则测试用例通过。 ?? ??? ??? ?assertTrue(x,[msg='测试失败时打印的信息']):断言x是否True,是True则测试用例通过。 ?? ??? ??? ?assertFalse(x,[msg='测试失败时打印的信息']):断言x是否False,是False则测试用例通过。 ?? ??? ??? ?assertIs(a,b,[msg='测试失败时打印的信息']):断言a是否是b,是则测试用例通过。 ?? ??? ??? ?assertIn(a,b,[msg='测试失败时打印的信息']):断言a是否在b中,在b中则测试用例通过。 ?? ??? ?c.提供了丰富的日志行为: ?? ??? ??? ?通过测试报告可以很清晰的查看用例总数、通过数、失败数量、环境信息。
2.unittest单元测试框架解析 ?? ?import unittest ?#导包 unitttest
?? ?class Integer(unittest.TestCase): ?? ?#Integer测试类的类名 ?? ?#单元测试框架中的测试类都要继承 ?unittest.TestCase类
?? ? ? ?def testAdd(self):## test method names begin 'test*' ? 重要:测试用例的命名必须以test开头******* ?? ? ? ? ? ?self.assertEqual(3, 3) ?? ? ? ? ? ?#assertEqual是断言的方法 用来判断a是否等于b ?? ? ? ? ? ?#assertEqual所有的断言都是来自unittest.TestCase类 ?? ? ? ? ?? ? ? ?def testMultiply(self): ?? ? ? ? ? ?self.assertEqual(0, 0)
?? ?if __name__ == '__main__': ? #运行整个的主函数入口 ?? ? ? ?unittest.main() ? ? #.main方法是unittest.TestLoader类下面提供的用来运行以test开头测试用例
3.unittest单元测试框架实例 ?? ?def add(a,b): ?? ? ? ?return a+b ?? ?def sub(a,b): ?? ? ? ?return a-b ?? ?def multi(a,b): ?? ? ? ?return a*b ?? ?def divide(a,b): ?? ? ? ?return a/b
?? ?import ?unittest
?? ?class Jisuan(unittest.TestCase): ?? ? ? ?def test_add(self): ?? ? ? ? ? ?self.assertEqual(30,add(1,2)) ?? ? ? ? ? ?# self.assertEqual(5,add(0,6)) ?? ? ? ? ? ? ?? ? ? ?def test_sub(self): ?? ? ? ? ? ?self.assertEqual(-2,sub(1,3))
?? ? ? ?def test_multi(self): ?? ? ? ? ? ?self.assertEqual(2,multi(1,2))
?? ? ? ?def test_divide(self): ?? ? ? ? ? ?self.assertEqual(50,divide(100,2))
?? ? ? ?def test_others(self): ?? ? ? ? ? ?a = 'hello' ?? ? ? ? ? ?self.assertIn(a,'helloworld')
?? ?if ?__name__=='__main__': ?? ? ? ?unittest.main()
4.unittest单元测试框架前置(setUp)和后置(tearDown)
?? ?前置条件:setUp() ?? ? ? setUp()方法用于测试用例执行前的初始化工作。如测试用例中需要访问数据库,可以在setUp中建立数据库连接并进行初始化。 ?? ? ? 如测试用例需要登录web,打开浏览器,最大化浏览器窗口,可以先实例化浏览器。
?? ?后置条件:tearDown() ?? ? ? tearDown()方法用于测试用例执行之后的善后工作。如关闭数据库连接,关闭浏览器等。
?? ?注意:前置和后置属于非必要条件。如果前置和后置,什么都不做,使用pass表示。
?? ?import ?unittest ?? ?class Jisuan(unittest.TestCase):
?? ? ? ?def setUp(self): ?? ? ? ? ? ?print 'begin to run testcase->' ?? ? ? ?def test_add(self): ?? ? ? ? ? ?print '===========+++++++==========>'
?? ? ? ?def test_others(self): ?? ? ? ? ? ?print '---------------------------->'
?? ? ? ?def tearDown(self): ?? ? ? ? ? ?print 'end stop run testcase--->'
?? ?if ?__name__=='__main__': ?? ? ? ?unittest.main()
?? ? 输出结果: ?? ? begin to run testcase-> ?? ?===========+++++++==========> ?? ?end stop run testcase---> ?? ?begin to run testcase-> ?? ?----------------------------> ?? ?end stop run testcase--->
5.unittest单元测试框架之断言 ?? ?assertEqual(a,b,[msg='测试失败时打印的信息']):断言a和b是否相等,相等则测试用例通过。 ?? ?assertNotEqual(a,b,[msg='测试失败时打印的信息']):断言a和b是否相等,不相等则测试用例通过。 ?? ?assertTrue(x,[msg='测试失败时打印的信息']):断言x是否True,是True则测试用例通过。 ?? ?assertFalse(x,[msg='测试失败时打印的信息']):断言x是否False,是False则测试用例通过。 ?? ?assertIs(a,b,[msg='测试失败时打印的信息']):断言a是否是b,是则测试用例通过。 ?? ?assertIn(a,b,[msg='测试失败时打印的信息']):断言a是否在b中,在b中则测试用例通过。
?? ?代码实例:
?? ?class Jisuan(unittest.TestCase): ?? ? ? ?# def setUp(self): ?? ? ? ?# ? ? print 'begin to run testcase->'
?? ? ? ?def test_add(self): ?? ? ? ? ? ?a='sddd' ?? ? ? ? ? ?b='hello' ?? ? ? ? ? ?self.assertIn(a,b,'测试用例不通过')
?? ? ? ?# def test_others(self): ?? ? ? ?# ? ? print '---------------------------->'
?? ? ? ?# def tearDown(self): ?? ? ? ?# ? ? print 'end stop run testcase--->'
?? ?if ?__name__=='__main__': ?? ? ? ?unittest.main()
6.unittest单元测试框架测试用例执行的顺序 ?? ?总结:以test后面的字符为参考点:数字优先/大写字母其后/小写字母最后(字母之间根据ascii码进行比较)
?? ??? ?import ?unittest ?? ??? ?class Jisuan(unittest.TestCase):
?? ??? ? ? ?# def setUp(self): ?? ??? ? ? ?# ? ? print 'begin to run testcase->'
?? ??? ? ? ?def test123(self): ?? ??? ? ? ? ? ?print 'en~~~~~~~~~~~~~~~~~~~~~~~~>'
?? ??? ? ? ?def testAbc(self): ?? ??? ? ? ? ? ?print '====================>'
?? ??? ? ? ?def testAthers(self): ?? ??? ? ? ? ? ?print '------------------------>'
?? ??? ? ? ?def testadd(self): ?? ??? ? ? ? ? ?print '++++++++++++++++++++++++>' ?? ??? ? ? ? ? ? ?? ??? ? ? ?# def tearDown(self): ?? ??? ? ? ?# ? ? print 'end stop run testcase--->'
?? ??? ?if ?__name__=='__main__': ?? ??? ? ? ?unittest.main()
7.使用unittest单元测试框架进行Web自动化测试用例编写
?? ?from selenium import webdriver ?? ?import unittest,time
?? ?class Youdao(unittest.TestCase):
?? ? ? ?def setUp(self): ?? ? ? ? ? ?self.driver = webdriver.Chrome() ?? ? ? ? ? ?self.driver.maximize_window() ?? ? ? ? ? ?self.base_url = "http://www.youdao.com"
?? ? ? ?def test_youdao(self): ?? ? ? ? ? ? ?? ? ? ? ? ?'''有道搜索_测试用例''' ?? ? ? ? ? ? ?? ? ? ? ? ?driver = self.driver ?? ? ? ? ? ?driver.get(self.base_url) ?? ? ? ? ? ?driver.find_element_by_name("q").clear() ?? ? ? ? ? ?driver.find_element_by_name("q").send_keys("webdriver") ?? ? ? ? ? ?driver.find_element_by_xpath("//*[@id='form']/button").click() ?? ? ? ? ? ?time.sleep(2) ?? ? ? ? ? ?driver.find_element_by_xpath("html/body/div[7]/i/a[1]").click() ?? ? ? ? ? ?text01 = driver.find_element_by_css_selector("span[class='keyword']").text ?? ? ? ? ? ?self.assertEqual(text01,'webdriver')
?? ? ? ?def tearDown(self): ?? ? ? ? ? ?self.driver.quit()
?? ?if __name__ == "__main__": ?? ? ? ?unittest.main()
六、生成HTML格式的测试报告 ?? ?#coding=utf-8
?? ?from HTMLTestRunner import ?HTMLTestRunner ? #导生成html格式的测试报告 ?? ?import unittest,time ?? ?import ?sys ?? ?reload(sys) ?? ?sys.setdefaultencoding('utf-8') ?#声明中文编码 utf-8 国际编码
?? ?test_case = r'E:\Project_case\unittest_demo\test_case' ?#定义测试用例所在文件夹 ?? ?test_list = unittest.defaultTestLoader.discover(test_case,pattern='test*.py') ?? ?#定义test_list用于查找test_case下面的以test开头的.py文件 ?? ?test_report = r'E:\Project_case\unittest_demo\test_report\\'
?? ?if __name__=="__main__": ?? ? ? ?now_time = time.strftime("%Y_%m_%d %H_%M_%S") ?? ? ? ?filename = test_report + now_time + 'result_.html' ?#定义测试报告文件名 ?? ? ? ?fp ?= open(filename,'wb') ?#读取filename文件 ?? ? ? ?runner = HTMLTestRunner(stream=fp, ?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?title=u'百度有道搜索自动化测试用例报告', ?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?description='Win10 ?Chrome 63.0 ?driver:2.33 selenium2.53.0 python2.7') ?? ? ? ?runner.run(test_list) ?#加载测试用例文件夹test_list ?? ? ? ?fp.close()
七、在windows下面创建定时任务计划 ?? ?1.在windows下面设置任务计划程序--开始--任务计划程序-操作-创建一个基本任务-触发器-操作-选择每天-下一步-启动程序-程序或脚本(本地主程序文件mian_test.py)-完成 ?? ?
单元测试框架源码: C:\Python27\python.exe E:/Project_case/demo.py Help on package unittest:
NAME ? ? unittest FILE ? ? c:\python27\lib\unittest\__init__.py DESCRIPTION ? ? Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's ? ? Smalltalk testing framework. ? ?? ? ? This module contains the core framework classes that form the basis of ? ? specific test cases and suites (TestCase, TestSuite etc.), and also a ? ? text-based utility class for running the tests and reporting the results ? ? ?(TextTestRunner). ? ?? ? ? Simple usage: ? ?? ? ? ? ? import unittest ? ?? ? ? ? ? class IntegerArithmeticTestCase(unittest.TestCase): ? ? ? ? ? ? def testAdd(self): ?## test method names begin 'test*' ? ? ? ? ? ? ? ? self.assertEqual((1 + 2), 3) ? ? ? ? ? ? ? ? self.assertEqual(0 + 1, 1) ? ? ? ? ? ? def testMultiply(self): ? ? ? ? ? ? ? ? self.assertEqual((0 * 10), 0) ? ? ? ? ? ? ? ? self.assertEqual((5 * 8), 40) ? ?? ? ? ? ? if __name__ == '__main__': ? ? ? ? ? ? unittest.main() ? ?? ? ? Further information is available in the bundled documentation, and from ? ?? ? ? ? http://docs.python.org/library/unittest.html ? ?? ? ? Copyright (c) 1999-2003 Steve Purcell ? ? Copyright (c) 2003-2010 Python Software Foundation ? ? This module is free software, and you may redistribute it and/or modify ? ? it under the same terms as Python itself, so long as this copyright message ? ? and disclaimer are retained in their original form. ? ?? ? ? IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, ? ? SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF ? ? THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH ? ? DAMAGE. ? ?? ? ? THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT ? ? LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ? ? PARTICULAR PURPOSE. ?THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, ? ? AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, ? ? SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
PACKAGE CONTENTS ? ? __main__ ? ? case ? ? loader ? ? main ? ? result ? ? runner ? ? signals ? ? suite ? ? test (package) ? ? util
CLASSES ? ? __builtin__.object ? ? ? ? unittest.case.TestCase ? ? ? ? ? ? unittest.case.FunctionTestCase ? ? ? ? unittest.loader.TestLoader ? ? ? ? unittest.main.TestProgram ? ? ? ? unittest.result.TestResult ? ? ? ? ? ? unittest.runner.TextTestResult ? ? ? ? unittest.runner.TextTestRunner ? ? exceptions.Exception(exceptions.BaseException) ? ? ? ? unittest.case.SkipTest ? ? unittest.suite.BaseTestSuite(__builtin__.object) ? ? ? ? unittest.suite.TestSuite ? ?? ? ? class FunctionTestCase(TestCase) ? ? ?| ?A test case that wraps a test function. ? ? ?| ? ? ? ?| ?This is useful for slipping pre-existing test functions into the ? ? ?| ?unittest framework. Optionally, set-up and tidy-up functions can be ? ? ?| ?supplied. As with TestCase, the tidy-up ('tearDown') function will ? ? ?| ?always be called if the set-up ('setUp') function ran successfully. ? ? ?| ? ? ? ?| ?Method resolution order: ? ? ?| ? ? ?FunctionTestCase ? ? ?| ? ? ?TestCase ? ? ?| ? ? ?__builtin__.object ? ? ?| ? ? ? ?| ?Methods defined here: ? ? ?| ? ? ? ?| ?__eq__(self, other) ? ? ?| ? ? ? ?| ?__hash__(self) ? ? ?| ? ? ? ?| ?__init__(self, testFunc, setUp=None, tearDown=None, description=None) ? ? ?| ? ? ? ?| ?__ne__(self, other) ? ? ?| ? ? ? ?| ?__repr__(self) ? ? ?| ? ? ? ?| ?__str__(self) ? ? ?| ? ? ? ?| ?id(self) ? ? ?| ? ? ? ?| ?runTest(self) ? ? ?| ? ? ? ?| ?setUp(self) ? ? ?| ? ? ? ?| ?shortDescription(self) ? ? ?| ? ? ? ?| ?tearDown(self) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Methods inherited from TestCase: ? ? ?| ? ? ? ?| ?__call__(self, *args, **kwds) ? ? ?| ? ? ? ?| ?addCleanup(self, function, *args, **kwargs) ? ? ?| ? ? ?Add a function, with arguments, to be called when the test is ? ? ?| ? ? ?completed. Functions added are called on a LIFO basis and are ? ? ?| ? ? ?called after tearDown on test failure or success. ? ? ?| ? ? ? ? ? ?| ? ? ?Cleanup items are called even if setUp fails (unlike tearDown). ? ? ?| ? ? ? ?| ?addTypeEqualityFunc(self, typeobj, function) ? ? ?| ? ? ?Add a type specific assertEqual style function to compare a type. ? ? ?| ? ? ? ? ? ?| ? ? ?This method is for use by TestCase subclasses that need to register ? ? ?| ? ? ?their own type equality functions to provide nicer error messages. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?typeobj: The data type to call this function on when both values ? ? ?| ? ? ? ? ? ? ? ? ?are of the same type in assertEqual(). ? ? ?| ? ? ? ? ?function: The callable taking two arguments and an optional ? ? ?| ? ? ? ? ? ? ? ? ?msg= argument that raises self.failureException with a ? ? ?| ? ? ? ? ? ? ? ? ?useful error message when the two arguments are not equal. ? ? ?| ? ? ? ?| ?assertAlmostEqual(self, first, second, places=None, msg=None, delta=None) ? ? ?| ? ? ?Fail if the two objects are unequal as determined by their ? ? ?| ? ? ?difference rounded to the given number of decimal places ? ? ?| ? ? ?(default 7) and comparing to zero, or by comparing that the ? ? ?| ? ? ?between the two objects is more than the given delta. ? ? ?| ? ? ? ? ? ?| ? ? ?Note that decimal places (from zero) are usually not the same ? ? ?| ? ? ?as significant digits (measured from the most significant digit). ? ? ?| ? ? ? ? ? ?| ? ? ?If the two objects compare equal then they will automatically ? ? ?| ? ? ?compare almost equal. ? ? ?| ? ? ? ?| ?assertAlmostEquals = assertAlmostEqual(self, first, second, places=None, msg=None, delta=None) ? ? ?| ? ? ?Fail if the two objects are unequal as determined by their ? ? ?| ? ? ?difference rounded to the given number of decimal places ? ? ?| ? ? ?(default 7) and comparing to zero, or by comparing that the ? ? ?| ? ? ?between the two objects is more than the given delta. ? ? ?| ? ? ? ? ? ?| ? ? ?Note that decimal places (from zero) are usually not the same ? ? ?| ? ? ?as significant digits (measured from the most significant digit). ? ? ?| ? ? ? ? ? ?| ? ? ?If the two objects compare equal then they will automatically ? ? ?| ? ? ?compare almost equal. ? ? ?| ? ? ? ?| ?assertDictContainsSubset(self, expected, actual, msg=None) ? ? ?| ? ? ?Checks whether actual is a superset of expected. ? ? ?| ? ? ? ?| ?assertDictEqual(self, d1, d2, msg=None) ? ? ?| ? ? ? ?| ?assertEqual(self, first, second, msg=None) ? ? ?| ? ? ?Fail if the two objects are unequal as determined by the '==' ? ? ?| ? ? ?operator. ? ? ?| ? ? ? ?| ?assertEquals = assertEqual(self, first, second, msg=None) ? ? ?| ? ? ?Fail if the two objects are unequal as determined by the '==' ? ? ?| ? ? ?operator. ? ? ?| ? ? ? ?| ?assertFalse(self, expr, msg=None) ? ? ?| ? ? ?Check that the expression is false. ? ? ?| ? ? ? ?| ?assertGreater(self, a, b, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a > b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertGreaterEqual(self, a, b, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a >= b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertIn(self, member, container, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a in b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertIs(self, expr1, expr2, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a is b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertIsInstance(self, obj, cls, msg=None) ? ? ?| ? ? ?Same as self.assertTrue(isinstance(obj, cls)), with a nicer ? ? ?| ? ? ?default message. ? ? ?| ? ? ? ?| ?assertIsNone(self, obj, msg=None) ? ? ?| ? ? ?Same as self.assertTrue(obj is None), with a nicer default message. ? ? ?| ? ? ? ?| ?assertIsNot(self, expr1, expr2, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a is not b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertIsNotNone(self, obj, msg=None) ? ? ?| ? ? ?Included for symmetry with assertIsNone. ? ? ?| ? ? ? ?| ?assertItemsEqual(self, expected_seq, actual_seq, msg=None) ? ? ?| ? ? ?An unordered sequence specific comparison. It asserts that ? ? ?| ? ? ?actual_seq and expected_seq have the same element counts. ? ? ?| ? ? ?Equivalent to:: ? ? ?| ? ? ? ? ? ?| ? ? ? ? ?self.assertEqual(Counter(iter(actual_seq)), ? ? ?| ? ? ? ? ? ? ? ? ? ? ? ? ? Counter(iter(expected_seq))) ? ? ?| ? ? ? ? ? ?| ? ? ?Asserts that each element has the same count in both sequences. ? ? ?| ? ? ?Example: ? ? ?| ? ? ? ? ?- [0, 1, 1] and [1, 0, 1] compare equal. ? ? ?| ? ? ? ? ?- [0, 0, 1] and [0, 1] compare unequal. ? ? ?| ? ? ? ?| ?assertLess(self, a, b, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a < b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertLessEqual(self, a, b, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a <= b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertListEqual(self, list1, list2, msg=None) ? ? ?| ? ? ?A list-specific equality assertion. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?list1: The first list to compare. ? ? ?| ? ? ? ? ?list2: The second list to compare. ? ? ?| ? ? ? ? ?msg: Optional message to use on failure instead of a list of ? ? ?| ? ? ? ? ? ? ? ? ?differences. ? ? ?| ? ? ? ?| ?assertMultiLineEqual(self, first, second, msg=None) ? ? ?| ? ? ?Assert that two multi-line strings are equal. ? ? ?| ? ? ? ?| ?assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None) ? ? ?| ? ? ?Fail if the two objects are equal as determined by their ? ? ?| ? ? ?difference rounded to the given number of decimal places ? ? ?| ? ? ?(default 7) and comparing to zero, or by comparing that the ? ? ?| ? ? ?between the two objects is less than the given delta. ? ? ?| ? ? ? ? ? ?| ? ? ?Note that decimal places (from zero) are usually not the same ? ? ?| ? ? ?as significant digits (measured from the most significant digit). ? ? ?| ? ? ? ? ? ?| ? ? ?Objects that are equal automatically fail. ? ? ?| ? ? ? ?| ?assertNotAlmostEquals = assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None) ? ? ?| ? ? ?Fail if the two objects are equal as determined by their ? ? ?| ? ? ?difference rounded to the given number of decimal places ? ? ?| ? ? ?(default 7) and comparing to zero, or by comparing that the ? ? ?| ? ? ?between the two objects is less than the given delta. ? ? ?| ? ? ? ? ? ?| ? ? ?Note that decimal places (from zero) are usually not the same ? ? ?| ? ? ?as significant digits (measured from the most significant digit). ? ? ?| ? ? ? ? ? ?| ? ? ?Objects that are equal automatically fail. ? ? ?| ? ? ? ?| ?assertNotEqual(self, first, second, msg=None) ? ? ?| ? ? ?Fail if the two objects are equal as determined by the '!=' ? ? ?| ? ? ?operator. ? ? ?| ? ? ? ?| ?assertNotEquals = assertNotEqual(self, first, second, msg=None) ? ? ?| ? ? ?Fail if the two objects are equal as determined by the '!=' ? ? ?| ? ? ?operator. ? ? ?| ? ? ? ?| ?assertNotIn(self, member, container, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a not in b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertNotIsInstance(self, obj, cls, msg=None) ? ? ?| ? ? ?Included for symmetry with assertIsInstance. ? ? ?| ? ? ? ?| ?assertNotRegexpMatches(self, text, unexpected_regexp, msg=None) ? ? ?| ? ? ?Fail the test if the text matches the regular expression. ? ? ?| ? ? ? ?| ?assertRaises(self, excClass, callableObj=None, *args, **kwargs) ? ? ?| ? ? ?Fail unless an exception of class excClass is raised ? ? ?| ? ? ?by callableObj when invoked with arguments args and keyword ? ? ?| ? ? ?arguments kwargs. If a different type of exception is ? ? ?| ? ? ?raised, it will not be caught, and the test case will be ? ? ?| ? ? ?deemed to have suffered an error, exactly as for an ? ? ?| ? ? ?unexpected exception. ? ? ?| ? ? ? ? ? ?| ? ? ?If called with callableObj omitted or None, will return a ? ? ?| ? ? ?context object used like this:: ? ? ?| ? ? ? ? ? ?| ? ? ? ? ? with self.assertRaises(SomeException): ? ? ?| ? ? ? ? ? ? ? do_something() ? ? ?| ? ? ? ? ? ?| ? ? ?The context manager keeps a reference to the exception as ? ? ?| ? ? ?the 'exception' attribute. This allows you to inspect the ? ? ?| ? ? ?exception after the assertion:: ? ? ?| ? ? ? ? ? ?| ? ? ? ? ?with self.assertRaises(SomeException) as cm: ? ? ?| ? ? ? ? ? ? ?do_something() ? ? ?| ? ? ? ? ?the_exception = cm.exception ? ? ?| ? ? ? ? ?self.assertEqual(the_exception.error_code, 3) ? ? ?| ? ? ? ?| ?assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs) ? ? ?| ? ? ?Asserts that the message in a raised exception matches a regexp. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?expected_exception: Exception class expected to be raised. ? ? ?| ? ? ? ? ?expected_regexp: Regexp (re pattern object or string) expected ? ? ?| ? ? ? ? ? ? ? ? ?to be found in error message. ? ? ?| ? ? ? ? ?callable_obj: Function to be called. ? ? ?| ? ? ? ? ?args: Extra args. ? ? ?| ? ? ? ? ?kwargs: Extra kwargs. ? ? ?| ? ? ? ?| ?assertRegexpMatches(self, text, expected_regexp, msg=None) ? ? ?| ? ? ?Fail the test unless the text matches the regular expression. ? ? ?| ? ? ? ?| ?assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None) ? ? ?| ? ? ?An equality assertion for ordered sequences (like lists and tuples). ? ? ?| ? ? ? ? ? ?| ? ? ?For the purposes of this function, a valid ordered sequence type is one ? ? ?| ? ? ?which can be indexed, has a length, and has an equality operator. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?seq1: The first sequence to compare. ? ? ?| ? ? ? ? ?seq2: The second sequence to compare. ? ? ?| ? ? ? ? ?seq_type: The expected datatype of the sequences, or None if no ? ? ?| ? ? ? ? ? ? ? ? ?datatype should be enforced. ? ? ?| ? ? ? ? ?msg: Optional message to use on failure instead of a list of ? ? ?| ? ? ? ? ? ? ? ? ?differences. ? ? ?| ? ? ? ?| ?assertSetEqual(self, set1, set2, msg=None) ? ? ?| ? ? ?A set-specific equality assertion. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?set1: The first set to compare. ? ? ?| ? ? ? ? ?set2: The second set to compare. ? ? ?| ? ? ? ? ?msg: Optional message to use on failure instead of a list of ? ? ?| ? ? ? ? ? ? ? ? ?differences. ? ? ?| ? ? ? ? ? ?| ? ? ?assertSetEqual uses ducktyping to support different types of sets, and ? ? ?| ? ? ?is optimized for sets specifically (parameters must support a ? ? ?| ? ? ?difference method). ? ? ?| ? ? ? ?| ?assertTrue(self, expr, msg=None) ? ? ?| ? ? ?Check that the expression is true. ? ? ?| ? ? ? ?| ?assertTupleEqual(self, tuple1, tuple2, msg=None) ? ? ?| ? ? ?A tuple-specific equality assertion. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?tuple1: The first tuple to compare. ? ? ?| ? ? ? ? ?tuple2: The second tuple to compare. ? ? ?| ? ? ? ? ?msg: Optional message to use on failure instead of a list of ? ? ?| ? ? ? ? ? ? ? ? ?differences. ? ? ?| ? ? ? ?| ?assert_ = assertTrue(self, expr, msg=None) ? ? ?| ? ? ?Check that the expression is true. ? ? ?| ? ? ? ?| ?countTestCases(self) ? ? ?| ? ? ? ?| ?debug(self) ? ? ?| ? ? ?Run the test without collecting errors in a TestResult ? ? ?| ? ? ? ?| ?defaultTestResult(self) ? ? ?| ? ? ? ?| ?doCleanups(self) ? ? ?| ? ? ?Execute all cleanup functions. Normally called for you after ? ? ?| ? ? ?tearDown. ? ? ?| ? ? ? ?| ?fail(self, msg=None) ? ? ?| ? ? ?Fail immediately, with the given message. ? ? ?| ? ? ? ?| ?failIf = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failIfAlmostEqual = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failIfEqual = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failUnless = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failUnlessAlmostEqual = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failUnlessEqual = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failUnlessRaises = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?run(self, result=None) ? ? ?| ? ? ? ?| ?skipTest(self, reason) ? ? ?| ? ? ?Skip this test. ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Class methods inherited from TestCase: ? ? ?| ? ? ? ?| ?setUpClass(cls) from __builtin__.type ? ? ?| ? ? ?Hook method for setting up class fixture before running tests in the class. ? ? ?| ? ? ? ?| ?tearDownClass(cls) from __builtin__.type ? ? ?| ? ? ?Hook method for deconstructing the class fixture after running all tests in the class. ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data descriptors inherited from TestCase: ? ? ?| ? ? ? ?| ?__dict__ ? ? ?| ? ? ?dictionary for instance variables (if defined) ? ? ?| ? ? ? ?| ?__weakref__ ? ? ?| ? ? ?list of weak references to the object (if defined) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data and other attributes inherited from TestCase: ? ? ?| ? ? ? ?| ?failureException = <type 'exceptions.AssertionError'> ? ? ?| ? ? ?Assertion failed. ? ? ?| ? ? ? ?| ?longMessage = False ? ? ?| ? ? ? ?| ?maxDiff = 640 ? ?? ? ? class SkipTest(exceptions.Exception) ? ? ?| ?Raise this exception in a test to skip it. ? ? ?| ? ? ? ?| ?Usually you can use TestCase.skipTest() or one of the skipping decorators ? ? ?| ?instead of raising this directly. ? ? ?| ? ? ? ?| ?Method resolution order: ? ? ?| ? ? ?SkipTest ? ? ?| ? ? ?exceptions.Exception ? ? ?| ? ? ?exceptions.BaseException ? ? ?| ? ? ?__builtin__.object ? ? ?| ? ? ? ?| ?Data descriptors defined here: ? ? ?| ? ? ? ?| ?__weakref__ ? ? ?| ? ? ?list of weak references to the object (if defined) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Methods inherited from exceptions.Exception: ? ? ?| ? ? ? ?| ?__init__(...) ? ? ?| ? ? ?x.__init__(...) initializes x; see help(type(x)) for signature ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data and other attributes inherited from exceptions.Exception: ? ? ?| ? ? ? ?| ?__new__ = <built-in method __new__ of type object> ? ? ?| ? ? ?T.__new__(S, ...) -> a new object with type S, a subtype of T ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Methods inherited from exceptions.BaseException: ? ? ?| ? ? ? ?| ?__delattr__(...) ? ? ?| ? ? ?x.__delattr__('name') <==> del x.name ? ? ?| ? ? ? ?| ?__getattribute__(...) ? ? ?| ? ? ?x.__getattribute__('name') <==> x.name ? ? ?| ? ? ? ?| ?__getitem__(...) ? ? ?| ? ? ?x.__getitem__(y) <==> x[y] ? ? ?| ? ? ? ?| ?__getslice__(...) ? ? ?| ? ? ?x.__getslice__(i, j) <==> x[i:j] ? ? ?| ? ? ? ? ? ?| ? ? ?Use of negative indices is not supported. ? ? ?| ? ? ? ?| ?__reduce__(...) ? ? ?| ? ? ? ?| ?__repr__(...) ? ? ?| ? ? ?x.__repr__() <==> repr(x) ? ? ?| ? ? ? ?| ?__setattr__(...) ? ? ?| ? ? ?x.__setattr__('name', value) <==> x.name = value ? ? ?| ? ? ? ?| ?__setstate__(...) ? ? ?| ? ? ? ?| ?__str__(...) ? ? ?| ? ? ?x.__str__() <==> str(x) ? ? ?| ? ? ? ?| ?__unicode__(...) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data descriptors inherited from exceptions.BaseException: ? ? ?| ? ? ? ?| ?__dict__ ? ? ?| ? ? ? ?| ?args ? ? ?| ? ? ? ?| ?message ? ?? ? ? class TestCase(__builtin__.object) ? ? ?| ?A class whose instances are single test cases. ? ? ?| ? ? ? ?| ?By default, the test code itself should be placed in a method named ? ? ?| ?'runTest'. ? ? ?| ? ? ? ?| ?If the fixture may be used for many test cases, create as ? ? ?| ?many test methods as are needed. When instantiating such a TestCase ? ? ?| ?subclass, specify in the constructor arguments the name of the test method ? ? ?| ?that the instance is to execute. ? ? ?| ? ? ? ?| ?Test authors should subclass TestCase for their own tests. Construction ? ? ?| ?and deconstruction of the test's environment ('fixture') can be ? ? ?| ?implemented by overriding the 'setUp' and 'tearDown' methods respectively. ? ? ?| ? ? ? ?| ?If it is necessary to override the __init__ method, the base class ? ? ?| ?__init__ method must always be called. It is important that subclasses ? ? ?| ?should not change the signature of their __init__ method, since instances ? ? ?| ?of the classes are instantiated automatically by parts of the framework ? ? ?| ?in order to be run. ? ? ?| ? ? ? ?| ?When subclassing TestCase, you can set these attributes: ? ? ?| ?* failureException: determines which exception will be raised when ? ? ?| ? ? ?the instance's assertion methods fail; test methods raising this ? ? ?| ? ? ?exception will be deemed to have 'failed' rather than 'errored'. ? ? ?| ?* longMessage: determines whether long messages (including repr of ? ? ?| ? ? ?objects used in assert methods) will be printed on failure in *addition* ? ? ?| ? ? ?to any explicit message passed. ? ? ?| ?* maxDiff: sets the maximum length of a diff in failure messages ? ? ?| ? ? ?by assert methods using difflib. It is looked up as an instance ? ? ?| ? ? ?attribute so can be configured by individual tests if required. ? ? ?| ? ? ? ?| ?Methods defined here: ? ? ?| ? ? ? ?| ?__call__(self, *args, **kwds) ? ? ?| ? ? ? ?| ?__eq__(self, other) ? ? ?| ? ? ? ?| ?__hash__(self) ? ? ?| ? ? ? ?| ?__init__(self, methodName='runTest') ? ? ?| ? ? ?Create an instance of the class that will use the named test ? ? ?| ? ? ?method when executed. Raises a ValueError if the instance does ? ? ?| ? ? ?not have a method with the specified name. ? ? ?| ? ? ? ?| ?__ne__(self, other) ? ? ?| ? ? ? ?| ?__repr__(self) ? ? ?| ? ? ? ?| ?__str__(self) ? ? ?| ? ? ? ?| ?addCleanup(self, function, *args, **kwargs) ? ? ?| ? ? ?Add a function, with arguments, to be called when the test is ? ? ?| ? ? ?completed. Functions added are called on a LIFO basis and are ? ? ?| ? ? ?called after tearDown on test failure or success. ? ? ?| ? ? ? ? ? ?| ? ? ?Cleanup items are called even if setUp fails (unlike tearDown). ? ? ?| ? ? ? ?| ?addTypeEqualityFunc(self, typeobj, function) ? ? ?| ? ? ?Add a type specific assertEqual style function to compare a type. ? ? ?| ? ? ? ? ? ?| ? ? ?This method is for use by TestCase subclasses that need to register ? ? ?| ? ? ?their own type equality functions to provide nicer error messages. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?typeobj: The data type to call this function on when both values ? ? ?| ? ? ? ? ? ? ? ? ?are of the same type in assertEqual(). ? ? ?| ? ? ? ? ?function: The callable taking two arguments and an optional ? ? ?| ? ? ? ? ? ? ? ? ?msg= argument that raises self.failureException with a ? ? ?| ? ? ? ? ? ? ? ? ?useful error message when the two arguments are not equal. ? ? ?| ? ? ? ?| ?assertAlmostEqual(self, first, second, places=None, msg=None, delta=None) ? ? ?| ? ? ?Fail if the two objects are unequal as determined by their ? ? ?| ? ? ?difference rounded to the given number of decimal places ? ? ?| ? ? ?(default 7) and comparing to zero, or by comparing that the ? ? ?| ? ? ?between the two objects is more than the given delta. ? ? ?| ? ? ? ? ? ?| ? ? ?Note that decimal places (from zero) are usually not the same ? ? ?| ? ? ?as significant digits (measured from the most significant digit). ? ? ?| ? ? ? ? ? ?| ? ? ?If the two objects compare equal then they will automatically ? ? ?| ? ? ?compare almost equal. ? ? ?| ? ? ? ?| ?assertAlmostEquals = assertAlmostEqual(self, first, second, places=None, msg=None, delta=None) ? ? ?| ? ? ? ?| ?assertDictContainsSubset(self, expected, actual, msg=None) ? ? ?| ? ? ?Checks whether actual is a superset of expected. ? ? ?| ? ? ? ?| ?assertDictEqual(self, d1, d2, msg=None) ? ? ?| ? ? ? ?| ?assertEqual(self, first, second, msg=None) ? ? ?| ? ? ?Fail if the two objects are unequal as determined by the '==' ? ? ?| ? ? ?operator. ? ? ?| ? ? ? ?| ?assertEquals = assertEqual(self, first, second, msg=None) ? ? ?| ? ? ? ?| ?assertFalse(self, expr, msg=None) ? ? ?| ? ? ?Check that the expression is false. ? ? ?| ? ? ? ?| ?assertGreater(self, a, b, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a > b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertGreaterEqual(self, a, b, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a >= b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertIn(self, member, container, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a in b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertIs(self, expr1, expr2, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a is b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertIsInstance(self, obj, cls, msg=None) ? ? ?| ? ? ?Same as self.assertTrue(isinstance(obj, cls)), with a nicer ? ? ?| ? ? ?default message. ? ? ?| ? ? ? ?| ?assertIsNone(self, obj, msg=None) ? ? ?| ? ? ?Same as self.assertTrue(obj is None), with a nicer default message. ? ? ?| ? ? ? ?| ?assertIsNot(self, expr1, expr2, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a is not b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertIsNotNone(self, obj, msg=None) ? ? ?| ? ? ?Included for symmetry with assertIsNone. ? ? ?| ? ? ? ?| ?assertItemsEqual(self, expected_seq, actual_seq, msg=None) ? ? ?| ? ? ?An unordered sequence specific comparison. It asserts that ? ? ?| ? ? ?actual_seq and expected_seq have the same element counts. ? ? ?| ? ? ?Equivalent to:: ? ? ?| ? ? ? ? ? ?| ? ? ? ? ?self.assertEqual(Counter(iter(actual_seq)), ? ? ?| ? ? ? ? ? ? ? ? ? ? ? ? ? Counter(iter(expected_seq))) ? ? ?| ? ? ? ? ? ?| ? ? ?Asserts that each element has the same count in both sequences. ? ? ?| ? ? ?Example: ? ? ?| ? ? ? ? ?- [0, 1, 1] and [1, 0, 1] compare equal. ? ? ?| ? ? ? ? ?- [0, 0, 1] and [0, 1] compare unequal. ? ? ?| ? ? ? ?| ?assertLess(self, a, b, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a < b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertLessEqual(self, a, b, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a <= b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertListEqual(self, list1, list2, msg=None) ? ? ?| ? ? ?A list-specific equality assertion. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?list1: The first list to compare. ? ? ?| ? ? ? ? ?list2: The second list to compare. ? ? ?| ? ? ? ? ?msg: Optional message to use on failure instead of a list of ? ? ?| ? ? ? ? ? ? ? ? ?differences. ? ? ?| ? ? ? ?| ?assertMultiLineEqual(self, first, second, msg=None) ? ? ?| ? ? ?Assert that two multi-line strings are equal. ? ? ?| ? ? ? ?| ?assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None) ? ? ?| ? ? ?Fail if the two objects are equal as determined by their ? ? ?| ? ? ?difference rounded to the given number of decimal places ? ? ?| ? ? ?(default 7) and comparing to zero, or by comparing that the ? ? ?| ? ? ?between the two objects is less than the given delta. ? ? ?| ? ? ? ? ? ?| ? ? ?Note that decimal places (from zero) are usually not the same ? ? ?| ? ? ?as significant digits (measured from the most significant digit). ? ? ?| ? ? ? ? ? ?| ? ? ?Objects that are equal automatically fail. ? ? ?| ? ? ? ?| ?assertNotAlmostEquals = assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None) ? ? ?| ? ? ? ?| ?assertNotEqual(self, first, second, msg=None) ? ? ?| ? ? ?Fail if the two objects are equal as determined by the '!=' ? ? ?| ? ? ?operator. ? ? ?| ? ? ? ?| ?assertNotEquals = assertNotEqual(self, first, second, msg=None) ? ? ?| ? ? ? ?| ?assertNotIn(self, member, container, msg=None) ? ? ?| ? ? ?Just like self.assertTrue(a not in b), but with a nicer default message. ? ? ?| ? ? ? ?| ?assertNotIsInstance(self, obj, cls, msg=None) ? ? ?| ? ? ?Included for symmetry with assertIsInstance. ? ? ?| ? ? ? ?| ?assertNotRegexpMatches(self, text, unexpected_regexp, msg=None) ? ? ?| ? ? ?Fail the test if the text matches the regular expression. ? ? ?| ? ? ? ?| ?assertRaises(self, excClass, callableObj=None, *args, **kwargs) ? ? ?| ? ? ?Fail unless an exception of class excClass is raised ? ? ?| ? ? ?by callableObj when invoked with arguments args and keyword ? ? ?| ? ? ?arguments kwargs. If a different type of exception is ? ? ?| ? ? ?raised, it will not be caught, and the test case will be ? ? ?| ? ? ?deemed to have suffered an error, exactly as for an ? ? ?| ? ? ?unexpected exception. ? ? ?| ? ? ? ? ? ?| ? ? ?If called with callableObj omitted or None, will return a ? ? ?| ? ? ?context object used like this:: ? ? ?| ? ? ? ? ? ?| ? ? ? ? ? with self.assertRaises(SomeException): ? ? ?| ? ? ? ? ? ? ? do_something() ? ? ?| ? ? ? ? ? ?| ? ? ?The context manager keeps a reference to the exception as ? ? ?| ? ? ?the 'exception' attribute. This allows you to inspect the ? ? ?| ? ? ?exception after the assertion:: ? ? ?| ? ? ? ? ? ?| ? ? ? ? ?with self.assertRaises(SomeException) as cm: ? ? ?| ? ? ? ? ? ? ?do_something() ? ? ?| ? ? ? ? ?the_exception = cm.exception ? ? ?| ? ? ? ? ?self.assertEqual(the_exception.error_code, 3) ? ? ?| ? ? ? ?| ?assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs) ? ? ?| ? ? ?Asserts that the message in a raised exception matches a regexp. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?expected_exception: Exception class expected to be raised. ? ? ?| ? ? ? ? ?expected_regexp: Regexp (re pattern object or string) expected ? ? ?| ? ? ? ? ? ? ? ? ?to be found in error message. ? ? ?| ? ? ? ? ?callable_obj: Function to be called. ? ? ?| ? ? ? ? ?args: Extra args. ? ? ?| ? ? ? ? ?kwargs: Extra kwargs. ? ? ?| ? ? ? ?| ?assertRegexpMatches(self, text, expected_regexp, msg=None) ? ? ?| ? ? ?Fail the test unless the text matches the regular expression. ? ? ?| ? ? ? ?| ?assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None) ? ? ?| ? ? ?An equality assertion for ordered sequences (like lists and tuples). ? ? ?| ? ? ? ? ? ?| ? ? ?For the purposes of this function, a valid ordered sequence type is one ? ? ?| ? ? ?which can be indexed, has a length, and has an equality operator. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?seq1: The first sequence to compare. ? ? ?| ? ? ? ? ?seq2: The second sequence to compare. ? ? ?| ? ? ? ? ?seq_type: The expected datatype of the sequences, or None if no ? ? ?| ? ? ? ? ? ? ? ? ?datatype should be enforced. ? ? ?| ? ? ? ? ?msg: Optional message to use on failure instead of a list of ? ? ?| ? ? ? ? ? ? ? ? ?differences. ? ? ?| ? ? ? ?| ?assertSetEqual(self, set1, set2, msg=None) ? ? ?| ? ? ?A set-specific equality assertion. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?set1: The first set to compare. ? ? ?| ? ? ? ? ?set2: The second set to compare. ? ? ?| ? ? ? ? ?msg: Optional message to use on failure instead of a list of ? ? ?| ? ? ? ? ? ? ? ? ?differences. ? ? ?| ? ? ? ? ? ?| ? ? ?assertSetEqual uses ducktyping to support different types of sets, and ? ? ?| ? ? ?is optimized for sets specifically (parameters must support a ? ? ?| ? ? ?difference method). ? ? ?| ? ? ? ?| ?assertTrue(self, expr, msg=None) ? ? ?| ? ? ?Check that the expression is true. ? ? ?| ? ? ? ?| ?assertTupleEqual(self, tuple1, tuple2, msg=None) ? ? ?| ? ? ?A tuple-specific equality assertion. ? ? ?| ? ? ? ? ? ?| ? ? ?Args: ? ? ?| ? ? ? ? ?tuple1: The first tuple to compare. ? ? ?| ? ? ? ? ?tuple2: The second tuple to compare. ? ? ?| ? ? ? ? ?msg: Optional message to use on failure instead of a list of ? ? ?| ? ? ? ? ? ? ? ? ?differences. ? ? ?| ? ? ? ?| ?assert_ = assertTrue(self, expr, msg=None) ? ? ?| ? ? ? ?| ?countTestCases(self) ? ? ?| ? ? ? ?| ?debug(self) ? ? ?| ? ? ?Run the test without collecting errors in a TestResult ? ? ?| ? ? ? ?| ?defaultTestResult(self) ? ? ?| ? ? ? ?| ?doCleanups(self) ? ? ?| ? ? ?Execute all cleanup functions. Normally called for you after ? ? ?| ? ? ?tearDown. ? ? ?| ? ? ? ?| ?fail(self, msg=None) ? ? ?| ? ? ?Fail immediately, with the given message. ? ? ?| ? ? ? ?| ?failIf = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failIfAlmostEqual = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failIfEqual = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failUnless = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failUnlessAlmostEqual = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failUnlessEqual = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?failUnlessRaises = deprecated_func(*args, **kwargs) ? ? ?| ? ? ? ?| ?id(self) ? ? ?| ? ? ? ?| ?run(self, result=None) ? ? ?| ? ? ? ?| ?setUp(self) ? ? ?| ? ? ?Hook method for setting up the test fixture before exercising it. ? ? ?| ? ? ? ?| ?shortDescription(self) ? ? ?| ? ? ?Returns a one-line description of the test, or None if no ? ? ?| ? ? ?description has been provided. ? ? ?| ? ? ? ? ? ?| ? ? ?The default implementation of this method returns the first line of ? ? ?| ? ? ?the specified test method's docstring. ? ? ?| ? ? ? ?| ?skipTest(self, reason) ? ? ?| ? ? ?Skip this test. ? ? ?| ? ? ? ?| ?tearDown(self) ? ? ?| ? ? ?Hook method for deconstructing the test fixture after testing it. ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Class methods defined here: ? ? ?| ? ? ? ?| ?setUpClass(cls) from __builtin__.type ? ? ?| ? ? ?Hook method for setting up class fixture before running tests in the class. ? ? ?| ? ? ? ?| ?tearDownClass(cls) from __builtin__.type ? ? ?| ? ? ?Hook method for deconstructing the class fixture after running all tests in the class. ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data descriptors defined here: ? ? ?| ? ? ? ?| ?__dict__ ? ? ?| ? ? ?dictionary for instance variables (if defined) ? ? ?| ? ? ? ?| ?__weakref__ ? ? ?| ? ? ?list of weak references to the object (if defined) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data and other attributes defined here: ? ? ?| ? ? ? ?| ?failureException = <type 'exceptions.AssertionError'> ? ? ?| ? ? ?Assertion failed. ? ? ?| ? ? ? ?| ?longMessage = False ? ? ?| ? ? ? ?| ?maxDiff = 640 ? ?? ? ? class TestLoader(__builtin__.object) ? ? ?| ?This class is responsible for loading tests according to various criteria ? ? ?| ?and returning them wrapped in a TestSuite ? ? ?| ? ? ? ?| ?Methods defined here: ? ? ?| ? ? ? ?| ?discover(self, start_dir, pattern='test*.py', top_level_dir=None) ? ? ?| ? ? ?Find and return all test modules from the specified start ? ? ?| ? ? ?directory, recursing into subdirectories to find them. Only test files ? ? ?| ? ? ?that match the pattern will be loaded. (Using shell style pattern ? ? ?| ? ? ?matching.) ? ? ?| ? ? ? ? ? ?| ? ? ?All test modules must be importable from the top level of the project. ? ? ?| ? ? ?If the start directory is not the top level directory then the top ? ? ?| ? ? ?level directory must be specified separately. ? ? ?| ? ? ? ? ? ?| ? ? ?If a test package name (directory with '__init__.py') matches the ? ? ?| ? ? ?pattern then the package will be checked for a 'load_tests' function. If ? ? ?| ? ? ?this exists then it will be called with loader, tests, pattern. ? ? ?| ? ? ? ? ? ?| ? ? ?If load_tests exists then discovery does ?*not* recurse into the package, ? ? ?| ? ? ?load_tests is responsible for loading all tests in the package. ? ? ?| ? ? ? ? ? ?| ? ? ?The pattern is deliberately not stored as a loader attribute so that ? ? ?| ? ? ?packages can continue discovery themselves. top_level_dir is stored so ? ? ?| ? ? ?load_tests does not need to pass this argument in to loader.discover(). ? ? ?| ? ? ? ?| ?getTestCaseNames(self, testCaseClass) ? ? ?| ? ? ?Return a sorted sequence of method names found within testCaseClass ? ? ?| ? ? ? ?| ?loadTestsFromModule(self, module, use_load_tests=True) ? ? ?| ? ? ?Return a suite of all tests cases contained in the given module ? ? ?| ? ? ? ?| ?loadTestsFromName(self, name, module=None) ? ? ?| ? ? ?Return a suite of all tests cases given a string specifier. ? ? ?| ? ? ? ? ? ?| ? ? ?The name may resolve either to a module, a test case class, a ? ? ?| ? ? ?test method within a test case class, or a callable object which ? ? ?| ? ? ?returns a TestCase or TestSuite instance. ? ? ?| ? ? ? ? ? ?| ? ? ?The method optionally resolves the names relative to a given module. ? ? ?| ? ? ? ?| ?loadTestsFromNames(self, names, module=None) ? ? ?| ? ? ?Return a suite of all tests cases found using the given sequence ? ? ?| ? ? ?of string specifiers. See 'loadTestsFromName()'. ? ? ?| ? ? ? ?| ?loadTestsFromTestCase(self, testCaseClass) ? ? ?| ? ? ?Return a suite of all tests cases contained in testCaseClass ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data descriptors defined here: ? ? ?| ? ? ? ?| ?__dict__ ? ? ?| ? ? ?dictionary for instance variables (if defined) ? ? ?| ? ? ? ?| ?__weakref__ ? ? ?| ? ? ?list of weak references to the object (if defined) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data and other attributes defined here: ? ? ?| ? ? ? ?| ?sortTestMethodsUsing = <built-in function cmp> ? ? ?| ? ? ?cmp(x, y) -> integer ? ? ?| ? ? ? ? ? ?| ? ? ?Return negative if x<y, zero if x==y, positive if x>y. ? ? ?| ? ? ? ?| ?suiteClass = <class 'unittest.suite.TestSuite'> ? ? ?| ? ? ?A test suite is a composite test consisting of a number of TestCases. ? ? ?| ? ? ? ? ? ?| ? ? ?For use, create an instance of TestSuite, then add test case instances. ? ? ?| ? ? ?When all tests have been added, the suite can be passed to a test ? ? ?| ? ? ?runner, such as TextTestRunner. It will run the individual test cases ? ? ?| ? ? ?in the order in which they were added, aggregating the results. When ? ? ?| ? ? ?subclassing, do not forget to call the base class constructor. ? ? ?| ? ? ? ?| ?testMethodPrefix = 'test' ? ?? ? ? class TestResult(__builtin__.object) ? ? ?| ?Holder for test result information. ? ? ?| ? ? ? ?| ?Test results are automatically managed by the TestCase and TestSuite ? ? ?| ?classes, and do not need to be explicitly manipulated by writers of tests. ? ? ?| ? ? ? ?| ?Each instance holds the total number of tests run, and collections of ? ? ?| ?failures and errors that occurred among those test runs. The collections ? ? ?| ?contain tuples of (testcase, exceptioninfo), where exceptioninfo is the ? ? ?| ?formatted traceback of the error that occurred. ? ? ?| ? ? ? ?| ?Methods defined here: ? ? ?| ? ? ? ?| ?__init__(self, stream=None, descriptions=None, verbosity=None) ? ? ?| ? ? ? ?| ?__repr__(self) ? ? ?| ? ? ? ?| ?addError(self, *args, **kw) ? ? ?| ? ? ?Called when an error has occurred. 'err' is a tuple of values as ? ? ?| ? ? ?returned by sys.exc_info(). ? ? ?| ? ? ? ?| ?addExpectedFailure(self, test, err) ? ? ?| ? ? ?Called when an expected failure/error occurred. ? ? ?| ? ? ? ?| ?addFailure(self, *args, **kw) ? ? ?| ? ? ?Called when an error has occurred. 'err' is a tuple of values as ? ? ?| ? ? ?returned by sys.exc_info(). ? ? ?| ? ? ? ?| ?addSkip(self, test, reason) ? ? ?| ? ? ?Called when a test is skipped. ? ? ?| ? ? ? ?| ?addSuccess(self, test) ? ? ?| ? ? ?Called when a test has completed successfully ? ? ?| ? ? ? ?| ?addUnexpectedSuccess(self, *args, **kw) ? ? ?| ? ? ?Called when a test was expected to fail, but succeed. ? ? ?| ? ? ? ?| ?printErrors(self) ? ? ?| ? ? ?Called by TestRunner after test run ? ? ?| ? ? ? ?| ?startTest(self, test) ? ? ?| ? ? ?Called when the given test is about to be run ? ? ?| ? ? ? ?| ?startTestRun(self) ? ? ?| ? ? ?Called once before any tests are executed. ? ? ?| ? ? ? ? ? ?| ? ? ?See startTest for a method called before each test. ? ? ?| ? ? ? ?| ?stop(self) ? ? ?| ? ? ?Indicates that the tests should be aborted ? ? ?| ? ? ? ?| ?stopTest(self, test) ? ? ?| ? ? ?Called when the given test has been run ? ? ?| ? ? ? ?| ?stopTestRun(self) ? ? ?| ? ? ?Called once after all tests are executed. ? ? ?| ? ? ? ? ? ?| ? ? ?See stopTest for a method called after each test. ? ? ?| ? ? ? ?| ?wasSuccessful(self) ? ? ?| ? ? ?Tells whether or not this result was a success ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data descriptors defined here: ? ? ?| ? ? ? ?| ?__dict__ ? ? ?| ? ? ?dictionary for instance variables (if defined) ? ? ?| ? ? ? ?| ?__weakref__ ? ? ?| ? ? ?list of weak references to the object (if defined) ? ?? ? ? class TestSuite(BaseTestSuite) ? ? ?| ?A test suite is a composite test consisting of a number of TestCases. ? ? ?| ? ? ? ?| ?For use, create an instance of TestSuite, then add test case instances. ? ? ?| ?When all tests have been added, the suite can be passed to a test ? ? ?| ?runner, such as TextTestRunner. It will run the individual test cases ? ? ?| ?in the order in which they were added, aggregating the results. When ? ? ?| ?subclassing, do not forget to call the base class constructor. ? ? ?| ? ? ? ?| ?Method resolution order: ? ? ?| ? ? ?TestSuite ? ? ?| ? ? ?BaseTestSuite ? ? ?| ? ? ?__builtin__.object ? ? ?| ? ? ? ?| ?Methods defined here: ? ? ?| ? ? ? ?| ?debug(self) ? ? ?| ? ? ?Run the tests without collecting errors in a TestResult ? ? ?| ? ? ? ?| ?run(self, result, debug=False) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Methods inherited from BaseTestSuite: ? ? ?| ? ? ? ?| ?__call__(self, *args, **kwds) ? ? ?| ? ? ? ?| ?__eq__(self, other) ? ? ?| ? ? ? ?| ?__init__(self, tests=()) ? ? ?| ? ? ? ?| ?__iter__(self) ? ? ?| ? ? ? ?| ?__ne__(self, other) ? ? ?| ? ? ? ?| ?__repr__(self) ? ? ?| ? ? ? ?| ?addTest(self, test) ? ? ?| ? ? ? ?| ?addTests(self, tests) ? ? ?| ? ? ? ?| ?countTestCases(self) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data descriptors inherited from BaseTestSuite: ? ? ?| ? ? ? ?| ?__dict__ ? ? ?| ? ? ?dictionary for instance variables (if defined) ? ? ?| ? ? ? ?| ?__weakref__ ? ? ?| ? ? ?list of weak references to the object (if defined) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data and other attributes inherited from BaseTestSuite: ? ? ?| ? ? ? ?| ?__hash__ = None ? ?? ? ? class TextTestResult(unittest.result.TestResult) ? ? ?| ?A test result class that can print formatted text results to a stream. ? ? ?| ? ? ? ?| ?Used by TextTestRunner. ? ? ?| ? ? ? ?| ?Method resolution order: ? ? ?| ? ? ?TextTestResult ? ? ?| ? ? ?unittest.result.TestResult ? ? ?| ? ? ?__builtin__.object ? ? ?| ? ? ? ?| ?Methods defined here: ? ? ?| ? ? ? ?| ?__init__(self, stream, descriptions, verbosity) ? ? ?| ? ? ? ?| ?addError(self, test, err) ? ? ?| ? ? ? ?| ?addExpectedFailure(self, test, err) ? ? ?| ? ? ? ?| ?addFailure(self, test, err) ? ? ?| ? ? ? ?| ?addSkip(self, test, reason) ? ? ?| ? ? ? ?| ?addSuccess(self, test) ? ? ?| ? ? ? ?| ?addUnexpectedSuccess(self, test) ? ? ?| ? ? ? ?| ?getDescription(self, test) ? ? ?| ? ? ? ?| ?printErrorList(self, flavour, errors) ? ? ?| ? ? ? ?| ?printErrors(self) ? ? ?| ? ? ? ?| ?startTest(self, test) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data and other attributes defined here: ? ? ?| ? ? ? ?| ?separator1 = '========================================================... ? ? ?| ? ? ? ?| ?separator2 = '--------------------------------------------------------... ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Methods inherited from unittest.result.TestResult: ? ? ?| ? ? ? ?| ?__repr__(self) ? ? ?| ? ? ? ?| ?startTestRun(self) ? ? ?| ? ? ?Called once before any tests are executed. ? ? ?| ? ? ? ? ? ?| ? ? ?See startTest for a method called before each test. ? ? ?| ? ? ? ?| ?stop(self) ? ? ?| ? ? ?Indicates that the tests should be aborted ? ? ?| ? ? ? ?| ?stopTest(self, test) ? ? ?| ? ? ?Called when the given test has been run ? ? ?| ? ? ? ?| ?stopTestRun(self) ? ? ?| ? ? ?Called once after all tests are executed. ? ? ?| ? ? ? ? ? ?| ? ? ?See stopTest for a method called after each test. ? ? ?| ? ? ? ?| ?wasSuccessful(self) ? ? ?| ? ? ?Tells whether or not this result was a success ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data descriptors inherited from unittest.result.TestResult: ? ? ?| ? ? ? ?| ?__dict__ ? ? ?| ? ? ?dictionary for instance variables (if defined) ? ? ?| ? ? ? ?| ?__weakref__ ? ? ?| ? ? ?list of weak references to the object (if defined) ? ?? ? ? class TextTestRunner(__builtin__.object) ? ? ?| ?A test runner class that displays results in textual form. ? ? ?| ? ? ? ?| ?It prints out the names of tests as they are run, errors as they ? ? ?| ?occur, and a summary of the results at the end of the test run. ? ? ?| ? ? ? ?| ?Methods defined here: ? ? ?| ? ? ? ?| ?__init__(self, stream=<open file '<stderr>', mode 'w'>, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None) ? ? ?| ? ? ? ?| ?run(self, test) ? ? ?| ? ? ?Run the given test case or test suite. ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data descriptors defined here: ? ? ?| ? ? ? ?| ?__dict__ ? ? ?| ? ? ?dictionary for instance variables (if defined) ? ? ?| ? ? ? ?| ?__weakref__ ? ? ?| ? ? ?list of weak references to the object (if defined) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data and other attributes defined here: ? ? ?| ? ? ? ?| ?resultclass = <class 'unittest.runner.TextTestResult'> ? ? ?| ? ? ?A test result class that can print formatted text results to a stream. ? ? ?| ? ? ? ? ? ?| ? ? ?Used by TextTestRunner. ? ?? ? ? main = class TestProgram(__builtin__.object) ? ? ?| ?A command-line program that runs a set of tests; this is primarily ? ? ?| ?for making test modules conveniently executable. ? ? ?| ? ? ? ?| ?Methods defined here: ? ? ?| ? ? ? ?| ?__init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=<unittest.loader.TestLoader object>, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None) ? ? ?| ? ? ? ?| ?createTests(self) ? ? ?| ? ? ? ?| ?parseArgs(self, argv) ? ? ?| ? ? ? ?| ?runTests(self) ? ? ?| ? ? ? ?| ?usageExit(self, msg=None) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data descriptors defined here: ? ? ?| ? ? ? ?| ?__dict__ ? ? ?| ? ? ?dictionary for instance variables (if defined) ? ? ?| ? ? ? ?| ?__weakref__ ? ? ?| ? ? ?list of weak references to the object (if defined) ? ? ?| ? ? ? ?| ?---------------------------------------------------------------------- ? ? ?| ?Data and other attributes defined here: ? ? ?| ? ? ? ?| ?USAGE = 'Usage: %(progName)s [options] [test] [...]\n\nOpti... ? ? ? ?... ? ? ?| ? ? ? ?| ?buffer = None ? ? ?| ? ? ? ?| ?catchbreak = None ? ? ?| ? ? ? ?| ?failfast = None ? ? ?| ? ? ? ?| ?progName = None
FUNCTIONS ? ? expectedFailure(func) ? ?? ? ? findTestCases(module, prefix='test', sortUsing=<built-in function cmp>, suiteClass=<class 'unittest.suite.TestSuite'>) ? ?? ? ? getTestCaseNames(testCaseClass, prefix, sortUsing=<built-in function cmp>) ? ?? ? ? installHandler() ? ?? ? ? makeSuite(testCaseClass, prefix='test', sortUsing=<built-in function cmp>, suiteClass=<class 'unittest.suite.TestSuite'>) ? ?? ? ? registerResult(result) ? ?? ? ? removeHandler(method=None) ? ?? ? ? removeResult(result) ? ?? ? ? skip(reason) ? ? ? ? Unconditionally skip a test. ? ?? ? ? skipIf(condition, reason) ? ? ? ? Skip a test if the condition is true. ? ?? ? ? skipUnless(condition, reason) ? ? ? ? Skip a test unless the condition is true.
DATA ? ? __all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner', 'T... ? ? defaultTestLoader = <unittest.loader.TestLoader object>
None
进程已结束,退出代码0
|