Budget App project - Python : Graph output

Hi everyone!

I have been working on the Budget App project for the Python certification and am having some trouble figuring out why is my code not passing the test. My code looks like this:

class Category:

    def __init__(self, name):
         self.name = name
         self.ledger = []
         self.amount_spent = 0
    def deposit(self, amount, description = ''):
         self.ledger.append({"amount": float(amount), "description": description})
    def get_balance(self):
        balance = 0
        for entry in self.ledger:
            for k, v in entry.items():
                try:
                    balance += v
                except:
                    pass
        return float(balance)
    def withdraw(self, amount, description = ''):
        if self.check_funds(amount) == True:
            self.ledger.append({"amount": float(-abs(amount)), "description": description})
            self.amount_spent += amount
            return True
        elif self.check_funds(amount) == False:
            return False
    def check_funds(self, amount):
        if self.get_balance() >= amount:
            return True
        elif self.get_balance() < amount:
            return False
    def transfer(self, amount, to):
        if self.check_funds(amount) == True:
            self.ledger.append({"amount": float(-abs(amount)), "description": f'Transfer to {to.name}'})
            to.ledger.append({"amount": float(amount), "description": f'Transfer from {self.name}'})
            return True
        elif self.check_funds(amount) == False:
            return False
    def __str__(self):
        topline = self.name.center(30, '*')
        next_line = ''
        last_line = f'Total: {self.get_balance():.2f}'
        space = ' ' * 2
        for entry in self.ledger:
            desc = entry["description"][:23]
            amt = f'{entry["amount"]:.2f}'[:7].rjust(30 - len(desc))
            next_line += f'{desc}{amt}\n'

        return f'{topline}\n{next_line}{last_line}'
def create_spend_chart(categories):
    total_spent = 0
    percent_cat = []
    name_list = []
    for category in categories:
        total_spent += category.amount_spent
    total_spent = round(total_spent, 2)
    for category in categories:
        percent_spent = (category.amount_spent / total_spent) * 100
        percent_cat.append(percent_spent)
    for category in categories:
        name_list.append(category.name)
    y_count = 100
    title_line = f'Percentage spent by category'
    y_line = ''
    dashes = '---' * len(percent_cat) + '-'
    x_line = dashes.rjust(len(dashes) + 4)
    len_list = []
    for name in name_list:
        len_list.append(len(name))
    name_looper = max(len_list)

    while y_count >= 0:
        pr_line = str(y_count).rjust(3)
        y_line += f'{pr_line}|'
        for value in percent_cat:
            if value >= y_count:
                y_line += f' o '
            else:
                y_line += '   '
        y_count -= 10
        y_line += f'\n'

    name_string = ''
    index = 0
    while (name_looper - 1) >= 0:
        for name in name_list:
            try:
                add = name[index]
                name_string += f' {add} '
            except:
                name_string += f'   '
                pass
        index += 1
        name_string += f'\n    '
        name_looper -= 1

    graph = f'{title_line}\n{y_line}{x_line}\n    {name_string}'



    return graph

And the test response is the following:

======================================================================
FAIL: test_create_spend_chart (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-budget-app/test_module.py", line 94, in test_create_spend_chart
    self.assertEqual(actual, expected, 'Expected different chart representation. Check that all spacing is exact.')
AssertionError: 'Perc[34 chars]     \n 90|         \n 80|         \n 70|    o[322 chars]    ' != 'Perc[34 chars]      \n 90|          \n 80|          \n 70|  [340 chars] t  '
Diff is 1271 characters long. Set self.maxDiff to None to see it. : Expected different chart representation. Check that all spacing is exact.

----------------------------------------------------------------------
Ran 11 tests in 0.011s

FAILED (failures=1)

From what I understand, I am missing spaces, and can’t find the way to add spaces without messing up my output.

-            n 
+            n  
?              +
-            t 
?              ^
+            t  ?              ^
-      : Expected different chart representation. Check that all spacing is exact.

The - lines are yours, the + lines are what’s expected. Your lines are a space short. It’s hard to tell from the test output at the end, but there is an extra line of spaces at the end of your chart that you need to remove as well.

As the output says, you can see this output if you add the self.maxDiff to the test in test_module.py like:

    def test_create_spend_chart(self):
        self.maxDiff = None

I made a couple of tweaks yesterday and was still getting it wrong. I added the self.maxDiff to the test a minute ago and got it right. Was that the thing making the difference?

Nope, that just gives you all the test output so you can better see the differences. It’s a good idea to set it on any test with which you are having trouble. You must have fixed something else as well.

I just tried it without adding it and it is back to showing me 1 Fail; if I paste

def test_create_spend_chart(self):
        self.maxDiff = None

right at the bottom of test.module.py, however, it returns OK. I feel like I am ‘cheating’ when I paste that and that is giving me the pass. Am I correct?

You can see the latest version of my code here:

https://replit.com/@HoracioRomo/boilerplate-budget-app?v=1

Thanks for your help!

I got it now; after adding and substracting spaces here and there, I finally made it work. Thanks for your input!

This means you have to add it you the test from which you wish to see more output, in this case, test_create_spend_chart. If you just paste

    def test_create_spend_chart(self):
        self.maxDiff = None

at the bottom of the file, you are creating a new test called test_create_spend_chart, which overrides the old one. And since the new one has no assertions, it always passes. Which is why your problem went away at first. So you take the original test and insert the self.maxDiff at the beginning:

    def test_create_spend_chart(self):
        self.maxDiff = None
        # the rest of the test code follows...

I should have been clearer. Yet another gotcha that’s obvious to one person and baffling to the other. Happens to me both ways, all the time.

Setting self.maxDiff always works on unittest tests (so all the fCC tests for python projects). I always set it on tests before I start working.

I later figured out that I was actually invalidating the first test, and thus passing. I kept at it and finally figured the issue with the spaces and legitimately passed the test; I am now doing the next one. Thanks for your help and patience!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.