Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Challenge: Mocking Internal Dependencies | Testing with unittest and pytest
Python Structural Programming
Osio 5. Luku 5
single

single

Challenge: Mocking Internal Dependencies

Pyyhkäise näyttääksesi valikon

You are about to face a magical challenge: as an apprentice wizard, you need to ensure your Magic Wand’s spell-casting script behaves correctly, even when the unpredictable forces of mana are at play. The wand relies on a function called get_mana_level() to sense the ambient magical energy. If the mana is high enough, your fiery spell bursts forth; if not, it fizzles into a disappointing puff. To test your spell reliably, you must mock the mana level, simulating both high and low magical energy.

Tehtävä

Pyyhkäise aloittaaksesi koodauksen

Your mission is to create a robust spell-casting system and test it using mocks.

  • Create a function get_mana_level() that returns a random integer from 0 to 100.
  • Create a function cast_spell() that:
    • Calls get_mana_level().
    • If the mana level is 50 or more, returns "Fireball cast successfully!".
    • Otherwise, returns "The spell fizzled...".
  • Write two tests using unittest:
    • Use patch to make get_mana_level() return 80, and check that cast_spell() returns the success message.
    • Use patch to make get_mana_level() return 20, and check that cast_spell() returns the fizzle message.

Hints:

  • Use random.randint in your get_mana_level() function.
  • To patch correctly, target 'get_mana_level' in your tests.

Ratkaisu

Switch to desktopVaihda työpöytään todellista harjoitusta vartenJatka siitä, missä olet käyttämällä jotakin alla olevista vaihtoehdoista
Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 5. Luku 5
single

single

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

some-alt