【问题标题】:First step with unit testing [closed]单元测试的第一步[关闭]
【发布时间】:2016-11-28 21:11:31
【问题描述】:

我想为此代码编写单元测试,但我不知道如何开始。 我需要为所有功能或其中一些我可以通过的功能编写单元测试?在我看来,我为 generate_id、add_note、remove_note 和 edit_note 编写单元测试,够吗? p>

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))

【问题讨论】:

    标签: python python-2.7 unit-testing testing


    【解决方案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/

    【讨论】:

    • 感谢您的回答!我写了一些单元测试,如果你愿意,可以检查一下。
    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2011-11-07
    • 2010-12-21
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多