samedi 26 septembre 2015

Python UnitTest and prohibiting certain values for class members

I'm hand-coding basic data structures with unit tests for practice.

I'm making a linked list node and only want it to be able to accept certain values for its next and previous node members. It should only accept another LinkedNode object or None. However, it's still accepting any values for this class member.

Any ideas on why?

LinkedNode class:

class LinkedNode():
  __slots__ = ['__value','__prev_node','__next_node']

  def __init__(self, value, prev_node=None, next_node=None):
    self.value = value
    self.prev_node = prev_node
    self.next_node = next_node

  @property
  def value(self):
    return self.__value

  @value.setter
  def value(self, value):
    self.__value = value

  @property
  def prev_node(self):
    return self.__prev_node

  @prev_node.setter
  def prev_node(self, prev_node):
    if isinstance(self, LinkedNode) or prev_node==None:
      self.__prev_node = prev_node
    else:
      raise ValueError('Can not set non LinkedNode object to member prev_node!')

  @property
  def next_node(self):
    return self.__next_node

  @next_node.setter
  def next_node(self, next_node):
    if isinstance(self, LinkedNode) or next_node==None:
      self.__next_node = next_node
    else:
      raise ValueError('Can not set non LinkedNode object to member next_node!')

test file:

import unittest
from linkednode import LinkedNode

class TestLinkedNode(unittest.TestCase):
  def test_init(self):
    node1 = LinkedNode(4)
    node2 = LinkedNode("string")

    #Checking value
    self.assertEqual(node1.value, 4)
    self.assertEqual(node2.value, "string")
    self.assertEqual(node1.prev_node, node1.next_node, None)

  def test_assignment(self):
    node1 = LinkedNode(4)
    node2 = LinkedNode("string")

    #Checking default values
    self.assertEqual(node1.prev_node, None)
    self.assertEqual(node1.next_node, None)

    #Checking Node Assignment
    try:
      node1.next_node = node2
      exception = False
    except:
      exception = True
    self.assertFalse(exception)

    exception = False
    try:
      node1.prev_node = "Bad Value"
    except:
      exception = True
    self.assertTrue(exception)

if __name__ == '__main__':
  unittest.main()

Aucun commentaire:

Enregistrer un commentaire