2020-06-09 15:59:19 +00:00
|
|
|
import unittest
|
2020-07-06 07:44:19 +00:00
|
|
|
|
2023-10-11 18:30:02 +00:00
|
|
|
import pytest
|
|
|
|
|
2020-11-27 09:57:12 +00:00
|
|
|
from knapsack import greedy_knapsack as kp
|
2020-06-09 15:59:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TestClass(unittest.TestCase):
|
|
|
|
"""
|
|
|
|
Test cases for knapsack
|
|
|
|
"""
|
|
|
|
|
|
|
|
def test_sorted(self):
|
|
|
|
"""
|
|
|
|
kp.calc_profit takes the required argument (profit, weight, max_weight)
|
|
|
|
and returns whether the answer matches to the expected ones
|
|
|
|
"""
|
|
|
|
profit = [10, 20, 30, 40, 50, 60]
|
|
|
|
weight = [2, 4, 6, 8, 10, 12]
|
|
|
|
max_weight = 100
|
2023-10-11 18:30:02 +00:00
|
|
|
assert kp.calc_profit(profit, weight, max_weight) == 210
|
2020-06-09 15:59:19 +00:00
|
|
|
|
|
|
|
def test_negative_max_weight(self):
|
|
|
|
"""
|
|
|
|
Returns ValueError for any negative max_weight value
|
|
|
|
:return: ValueError
|
|
|
|
"""
|
|
|
|
# profit = [10, 20, 30, 40, 50, 60]
|
|
|
|
# weight = [2, 4, 6, 8, 10, 12]
|
|
|
|
# max_weight = -15
|
2023-10-11 18:30:02 +00:00
|
|
|
pytest.raises(ValueError, match="max_weight must greater than zero.")
|
2020-06-09 15:59:19 +00:00
|
|
|
|
|
|
|
def test_negative_profit_value(self):
|
|
|
|
"""
|
|
|
|
Returns ValueError for any negative profit value in the list
|
|
|
|
:return: ValueError
|
|
|
|
"""
|
|
|
|
# profit = [10, -20, 30, 40, 50, 60]
|
|
|
|
# weight = [2, 4, 6, 8, 10, 12]
|
|
|
|
# max_weight = 15
|
2023-10-11 18:30:02 +00:00
|
|
|
pytest.raises(ValueError, match="Weight can not be negative.")
|
2020-06-09 15:59:19 +00:00
|
|
|
|
|
|
|
def test_negative_weight_value(self):
|
|
|
|
"""
|
|
|
|
Returns ValueError for any negative weight value in the list
|
|
|
|
:return: ValueError
|
|
|
|
"""
|
|
|
|
# profit = [10, 20, 30, 40, 50, 60]
|
|
|
|
# weight = [2, -4, 6, -8, 10, 12]
|
|
|
|
# max_weight = 15
|
2023-10-11 18:30:02 +00:00
|
|
|
pytest.raises(ValueError, match="Profit can not be negative.")
|
2020-06-09 15:59:19 +00:00
|
|
|
|
|
|
|
def test_null_max_weight(self):
|
|
|
|
"""
|
|
|
|
Returns ValueError for any zero max_weight value
|
|
|
|
:return: ValueError
|
|
|
|
"""
|
|
|
|
# profit = [10, 20, 30, 40, 50, 60]
|
|
|
|
# weight = [2, 4, 6, 8, 10, 12]
|
|
|
|
# max_weight = null
|
2023-10-11 18:30:02 +00:00
|
|
|
pytest.raises(ValueError, match="max_weight must greater than zero.")
|
2020-06-09 15:59:19 +00:00
|
|
|
|
|
|
|
def test_unequal_list_length(self):
|
|
|
|
"""
|
|
|
|
Returns IndexError if length of lists (profit and weight) are unequal.
|
|
|
|
:return: IndexError
|
|
|
|
"""
|
|
|
|
# profit = [10, 20, 30, 40, 50]
|
|
|
|
# weight = [2, 4, 6, 8, 10, 12]
|
|
|
|
# max_weight = 100
|
2023-10-11 18:30:02 +00:00
|
|
|
pytest.raises(IndexError, match="The length of profit and weight must be same.")
|
2020-06-09 15:59:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
unittest.main()
|