Question

I need some tests for this python class. some tests for some of the functions in...

I need some tests for this python class. some tests for some of the functions in this class like.

def __init__
def __eq__
def __lt__
def __hash__

I am using Pycharm and useing Pytest to write some tests but have no idea how to write one

---------------------------------------------------------------------------------------------------
class Movie:

    def __set_title_internal(self, title: str):
        if title.strip() == "" or type(title) is not str:
            self.__title = None
        else:
            self.__title = title.strip()

    def __set_release_year_internal(self, release_year: int):
        if release_year >= 1900 and type(release_year) is int:
            self.__release_year = release_year
        else:
            self.__release_year = None

    def __init__(self, title: str, release_year: int):

        self.__set_title_internal(title)
        self.__set_release_year_internal(release_year)

        self.__description = None
        self.__director = None
        self.__actors = []
        self.__genres = []
        self.__runtime_minutes = None

    # essential attributes

    @property
    def title(self) -> str:
        return self.__title

    @title.setter
    def title(self, title: str):
        self.__set_title_internal(title)

    @property
    def release_year(self) -> int:
        return self.__release_year

    @release_year.setter
    def release_year(self, release_year: int):
        self.__set_release_year_internal(release_year)

    # additional attributes

    @property
    def description(self) -> str:
        return self.__description

    @description.setter
    def description(self, description: str):
        if type(description) is str:
            self.__description = description.strip()
        else:
            self.__description = None

    @property
    def director(self) -> Director:
        return self.__director

    @director.setter
    def director(self, director: Director):
        if isinstance(director, Director):
            self.__director = director
        else:
            self.__director = None

    @property
    def actors(self) -> list:
        return self.__actors

    def add_actor(self, actor: Actor):
        if not isinstance(actor, Actor) or actor in self.__actors:
            return

        self.__actors.append(actor)

    def remove_actor(self, actor: Actor):
        if not isinstance(actor, Actor):
            return

        try:
            self.__actors.remove(actor)
        except ValueError:
            # print(f"Movie.remove_actor: Could not find {actor} in list of actors.")
            pass

    @property
    def genres(self) -> list:
        return self.__genres

    def add_genre(self, genre: Genre):
        if not isinstance(genre, Genre) or genre in self.__genres:
            return

        self.__genres.append(genre)

    def remove_genre(self, genre: Genre):
        if not isinstance(genre, Genre):
            return

        try:
            self.__genres.remove(genre)
        except ValueError:
            # print(f"Movie.remove_genre: Could not find {genre} in list of genres.")
            pass

    @property
    def runtime_minutes(self) -> int:
        return self.__runtime_minutes

    @runtime_minutes.setter
    def runtime_minutes(self, val: int):
        if val > 0:
            self.__runtime_minutes = val
        else:
            raise ValueError(f'Movie.runtime_minutes setter: Value out of range {val}')

    def __get_unique_string_rep(self):
        return f"{self.__title}, {self.__release_year}"

    def __repr__(self):
        return f''

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return False
        return self.__get_unique_string_rep() == other.__get_unique_string_rep()

    def __lt__(self, other):
        if self.title == other.title:
            return self.release_year < other.release_year
        return self.title < other.title

    def __hash__(self):
        return hash(self.__get_unique_string_rep())

Homework Answers

Answer #1

We write unit test cases by asserting something. Commonly used ones are assertTrue(), assertFalse(), assertEqual(), etc. I have written sample test cases to test __init__() and __eq__(). You can write your test cases similarly.

Python3 code:

class TestMovie(unittest.TestCase):
#testing if values are being set properly
def test_init(self):
movie = Movie("The good, the bad and the ugly", 1967)
self.assertEqual(movie.title, "The good, the bad and the ugly")
self.assertEqual(movie.release_year, 1967)
#testing if the function is checking the instance properly
def test__eq__(self):
movie = Movie("The good, the bad and the ugly", 1967)
self.assertTrue(movie.__eq__(Movie("The good, the bad and the ugly", 1967)))
self.assertFalse(movie.__eq__(Movie("The good and the ugly", 1967)))
if __name__ == '__main__':
unittest.main()

Here we have run 2 tests.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Using Classes This problem relates to the pre-loaded class Person. Using the Person class, write a...
Using Classes This problem relates to the pre-loaded class Person. Using the Person class, write a function print_friend_info(person) which accepts a single argument, of type Person, and: prints out their name prints out their age if the person has any friends, prints 'Friends with {name}' Write a function create_fry() which returns a Person instance representing Fry. Fry is 25 and his full name is 'Philip J. Fry' Write a function make_friends(person_one, person_two) which sets each argument as the friend of...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
Python ------------------------- ### Description In this exercise, you will add to your `Battery` class a method...
Python ------------------------- ### Description In this exercise, you will add to your `Battery` class a method to drain the battery. ### Class Name `Battery` ### Method `drain()` ### Parameters * `self` : the `Battery` object to use * `milliamps` : a number, the amount of charge to remove from the battery. ### Action Removes `milliamps` from the charge of the object. If the new charge is less than 0, then set the charge to 0. Only do this action of...
"""linkedQueue.py implements LinkedQueue""" class Node(object): def __init__(self, e, nextNode): self.item, self.next = (e, nextNode) def __str__(self):...
"""linkedQueue.py implements LinkedQueue""" class Node(object): def __init__(self, e, nextNode): self.item, self.next = (e, nextNode) def __str__(self): return str(self.item)    class LinkedQueue(object): def __init__(self): #O(1) self._front, self._rear =(None, None) self._size = 0    def enqueue(self, e): # add e to the rear of the queue. newTail = Node(e, None) if self.isEmpty(): self._front = newTail else: self._rear.next = newTail self._rear = newTail self._size += 1 def front(self): # raise exception if it is empty, otherwise return front element if self.isEmpty(): raise Exception("call...
Hello, I created a class in Python and am struggling to figure out how to complete...
Hello, I created a class in Python and am struggling to figure out how to complete the last part. How can you verify that a date is before in a pythonic way? I am struggling with the operands and what to check first. Thank you! class Date(object): "Represents a Calendar date" def __init__(self, day=0, month=0, year=0): "Initialize" self.day = day self.month = month self.year = year def __str__(self): "Return a printable string representing the date: m/d/y" return f'{self.month}/{self.day}/{self.year}' def before(self,...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will look like: Enter number of players: 2 Player 1: 7S 5D - 12 points Player 2: 4H JC - 14 points Dealer: 10D Player 1, do you want to hit? [y / n]: y Player 1: 7S 5D 8H - 20 points Player 1, do you want to hit? [y / n]: n Player 2, do you want to hit? [y / n]: y...
Please create a python module named homework.py and implement the functions outlined below. Below you will...
Please create a python module named homework.py and implement the functions outlined below. Below you will find an explanation for each function you need to implement. When you are done please upload the file homework.py to Grader Than. Please get started as soon as possible on this assignment. This assignment has many problems, it may take you longer than normal to complete this assignment. This assignment is supposed to test you on your understanding of reading and writing to a...
Python recursive design question: Background: The class vote creates vote objects. A vote is either a...
Python recursive design question: Background: The class vote creates vote objects. A vote is either a blue vote, a red vote, or a purple. This information is stored in the "value" attribute. The function Poll returns a list of random votes. In the code below, some_poll is a list of 32 random votes. some_poll = Poll(32) # ----------------------------------------------------- import random # ----------------------------------------------------- # # Return a list of n random votes # # ----------------------------------------------------- def Poll(n=16): # # A random...
"""Prep 7 Synthesize === CSC148 Fall 2020 === Department of Mathematical and Computational Sciences, University of...
"""Prep 7 Synthesize === CSC148 Fall 2020 === Department of Mathematical and Computational Sciences, University of Toronto Mississauga === Module Description === Your task in this prep is to implement each of the unimplemented Tree methods in this file. The starter code has a recursive template that includes the "size-one" case; you may or may not choose to use this in your final implementations. """ from __future__ import annotations from typing import Any, List, Optional class Tree: """A recursive tree...