02 标准库

2.1 json

两对、四个主要使用的函数dump load dumps loads。前两个是在是在文件中保存和加载json数据,后两个则是在字符串中保存和加载数据。

  • dump():把数据以json格式存放在文件中。第一个参数是要保存的python对象,第二个参数是文件对象

  • load():从json格式的文件中读取数据。

import json
info = {
'name': 'leo sirius',
'age': 24,
'gender': None,
}
filename = 'person_info.json'
with open(filename, 'w') as f_ojb:
json.dump(info, f_ojb)

person_info.json文件中的内容

{name: leo sirius, age: 24, gender: null}

再用load读取文件

import json
filename = 'person_info.json'
with open(filename) as f_ojb:
info = json.load(f_ojb)
print(info) # 会输出 {'name': 'leo sirius', 'age': 24, 'gender': None}

dumps和loads也有类似的作用,只不过是把json存放在字符串中。

2.2 unittest

unittest.TestCase中的断言方法

下面是部分常用方法

方法

用途

assertEqual(a, b)

a == b

assertNotEqual(a, b)

a != b

assertTrue(x)

x == True

assertFalse(x)

x == False

assertIn(item, list)

item in list

assertNotIn(item, list)

item not in list

一个例子

用一个实际的例子来说明unittest的使用。我们创建一个抽象的AnonymousSurvey类来模拟一个问卷调查,这个类有存储答案和展示结果的功能。

# survey.py
class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
print('Survey results:')
for response in self.responses:
print('- ' + response)
from survey import AnonymousSurvey
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.show_question()
print('Enter "q" ay any time to quit.\n')
while True:
response = input("Language: ")
if response == 'q':
break
my_survey.store_response(response)
print('\nThank you to everyone who participated in the survey!')
my_survey.show_results()

运行结果

[email protected] py_tmp (master) $ python3 language_survey.py
What language did you first learn to speak?
Enter "q" ay any time to quit.
Language: English
Language: Spanish
Language: Mandarin
Language: Japanese
Language: q
Thank you to everyone who participated in the survey!
Survey results:
- English
- Spanish
- Mandarin
- Japanese

接下来我们来写测试

# test_survey.py
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
question = 'What language did you first learn to speak?'
self.my_survey = AnonymousSurvey(question)
self.responses = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_response(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
unittest.main()
[email protected] py_tmp (master) $ python3 test_survey.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OKOKOK