lundi 28 novembre 2016

First step with unit testing [python]

I want to write unit test for this code but I don't know how to start. I need to write unit test for all functions or some of them I can pass? In my opinion I write unit test for generate_id , add_note, remove_note and edit_note, is that enough?

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)

Aucun commentaire:

Enregistrer un commentaire