单元测试的第一步

时间:2016-11-28 21:11:31

标签: python python-2.7 unit-testing testing

我想为这段代码编写单元测试,但我不知道如何开始。 我需要为所有函数编写单元测试,或者我可以通过哪些函数?在我看来,我为 generate_id add_note remove_note edit_note 编写单元测试,这还够吗?

import json

def get_notes_data(file_name):
    with open(file_name, 'r') as open_file:
        return json.loads(open_file.read(), encoding='utf-8')


notes = get_notes_data('notes_data/notes.json')

def print_column(column_name):
    list_of_notes = [note for note in notes if note['board'] == column_name]
    return [note['message'] for note in notes if note['board'] == column_name]

#lista = print_column('to do')

def print_data():
    all_columns = [note['board'] for note in notes]
    columns = set(all_columns)
    for column in columns:
        print column
        print '\n'
        print print_column(column)
        print '\n \n'


def generate_id():
    max_id = 0
    for note in get_notes_data('notes_data/notes.json'):
        if note['id'] > max_id:
            max_id = note['id']
    return max_id + 1

def save_notes(file_name, notes):
    with open(file_name, 'w') as notes_file:
        json.dump(notes, notes_file, indent=4)

def add_note(column_name, note_message, notes):
    note_data = {"board" : column_name, 
            "message": note_message,
            "id": generate_id()}
    notes.append(note_data)
    save_notes('notes_data/notes.json', notes)
    return note_data


def remove_note(note_id, notes):
    for note in notes:
        if note['id'] == note_id:
            notes.pop(notes.index(note))
    save_notes('notes_data/notes.json', notes)


def edit_note(note_id, message, board, notes):
    changed = False
    for note in notes:
        if note['id'] == note_id:
            note['message'] = message
            note['board'] = board
            changed = True
    if not changed:
        raise IndexError('Index {0} does not exist'.format(note_id))
    save_notes('notes_data/notes.json', notes)
某些单元测试:

def test_generate_id(self):
    expected = 10
    actual = first.generate_id()
    self.assertEqual(expected, actual)

def test_add_note(self):
    column_name = 'to do'
    note_message = 'message to Damian'
    idx = first.generate_id()
    new_note = {"message":note_message, 'id': idx, 'board':column_name}
    first.add_note(column_name, note_message, TestFirst.data)
    notes = first.get_notes_data(TestFirst.DATABASE)
    self.assertIn(new_note, notes)

def test_remove_note(self):
    idx = 7
    notes = first.get_notes_data(TestFirst.DATABASE)
    for note in notes:
        if note['id'] == idx:
            to_remove = note
    first.remove_note(idx, notes)
    self.assertNotIn(to_remove, notes)

def test_edit_note_fail(self):
    note_id = 99
    message = "except error"
    board = "to do"
    notes = first.get_notes_data(TestFirst.DATABASE)
    self.assertRaises(IndexError, lambda:first.edit_note(note_id, message, board, notes))

1 个答案:

答案 0 :(得分:1)

查看unittest.TestCase模块。见https://docs.python.org/2/library/unittest.html

你想要做类似

的事情
from unittest import TestCase

class MyTests(TestCase):

    def setUp(self):
        # Do test setups here
        pass

    def test_my_method_1(self):
        pass

    def test_my_method_2(self):
        pass

等。

至于测试什么,有各种工具可以为您提供分支覆盖和线路覆盖。覆盖率百分比因意见而异,但一般的经验法则是拍摄80%的覆盖率。

此外,您应该考虑通过传入参数来使您的函数更容易测试。例如:

def generate_id():
    max_id = 0
    for note in get_notes_data('notes_data/notes.json'):
        if note['id'] > max_id:
            max_id = note['id']
    return max_id + 1

可以成为

def generate_id(notes_data):
    max_id = 0
    for note in notes_data:
        if note['id'] > max_id:
            max_id = note['id']
    return max_id + 1

然后通过传入一些模拟的笔记数据并测试返回值,为这种情况编写一个独立的测试要容易得多

对此的测试可能如下所示:

def test_generate_id(self):
   notes_data = { 'id': 1 }
   actual = generate_id(notes_data)
   expected = 2
   self.assertEquals(actual, expected)

您可以使用nosetests命令运行测试。 http://nose.readthedocs.io/en/latest/