Skip to content
Snippets Groups Projects
Commit 6e48679f authored by Alma Berisha's avatar Alma Berisha
Browse files

init3

parent b9c6cd1c
No related branches found
No related tags found
No related merge requests found
from abc import ABC, abstractmethod
import unittest
class IStringCalculator(ABC):
@abstractmethod
def add(self, numbers: str) -> int:
pass
class StringCalculator(IStringCalculator):
def add(self, numbers: str) -> int:
if not numbers:
return 0
# Ersetze Zeilenumbrüche durch Kommas und teile die Eingabe nach Kommas
numbers = numbers.replace("\n", ",")
# Splitte die Zahlen und prüfe auf negative Zahlen
nums = numbers.split(',')
negatives = [num for num in nums if int(num) < 0]
if negatives:
# Wenn negative Zahlen vorhanden sind, werfe eine Ausnahme
raise ValueError(f"Negatives not allowed: {', '.join(negatives)}")
# Berechne die Summe der positiven Zahlen
return sum(map(int, nums))
class TestStringCalculator(unittest.TestCase):
def setUp(self):
self.calculator = StringCalculator()
def test_empty_string(self):
self.assertEqual(self.calculator.add(""), 0)
def test_single_number(self):
self.assertEqual(self.calculator.add("1"), 1)
def test_two_numbers(self):
self.assertEqual(self.calculator.add("1,2"), 3)
def test_multiple_numbers(self):
self.assertEqual(self.calculator.add("1,2,3,4,5"), 15)
def test_numbers_with_newline(self):
self.assertEqual(self.calculator.add("1\n2,3"), 6)
def test_numbers_with_multiple_newlines(self):
self.assertEqual(self.calculator.add("1\n2\n3\n4\n5"), 15)
def test_negative_number(self):
with self.assertRaises(ValueError) as context:
self.calculator.add("1,-2,3")
self.assertEqual(str(context.exception), "Negatives not allowed: -2")
def test_multiple_negative_numbers(self):
with self.assertRaises(ValueError) as context:
self.calculator.add("1,-2,-3,4")
self.assertEqual(str(context.exception), "Negatives not allowed: -2, -3")
if __name__ == "__main__":
unittest.main()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment