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
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 {...
"""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...
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...
def clear(file_path: str): """ Clears the file at the specified file path. :param file_path: A path...
def clear(file_path: str): """ Clears the file at the specified file path. :param file_path: A path to a file :return: None """ def delete_last_line(file_path: str) -> str: """ Removes the last line in the file at the specified file path. Then it saves the new value with the last line removed to the file. Finally it returns the deleted last line. If the file has nothing in it an empty string ("") is returned. :param file_path: A path to file...
Python #Imagine you're writing a program to check if a person is #available at a certain...
Python #Imagine you're writing a program to check if a person is #available at a certain time. # #To do this, you want to write a function called #check_availability. check_availability will have two #parameters: a list of instances of the Meeting class, and #proposed_time, a particular date and time. # #check_availability should return True (meaning the person #is available) if there are no instances of Meeting that #conflict with the proposed_time. In other words, it should #return False if proposed_time...
Can someone please edit my code so that it satisfies the assignments' requirements? I pasted the...
Can someone please edit my code so that it satisfies the assignments' requirements? I pasted the codes below. Requirement: Goals for This Project:  Using class to model Abstract Data Type  OOP-Data Encapsulation You are asked to write an app to keep track of a relatively small music library. The app should load song information from a data file once the app is started. It should allow user to view, add, remove, and search for songs. The app should...
#########################PANDAS LANGUAGE################## #########################MATPLOT LIB######################### # filter the movies with specific actor's name ​# List of top...
#########################PANDAS LANGUAGE################## #########################MATPLOT LIB######################### # filter the movies with specific actor's name ​# List of top 5 Actor per year who has highest rating from the year 2010 - 2017 ​# plot horizontal barcahrt of upper output # visualize those to 10 runtime of movies ​# visualize those to 10 runtime which has highest rating of movies ​# show count all movies which has rating more 3.0 and less than 7.0​ # plot vertical barchart of upper output, movies w.r.t...