Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
undefined variables
#11
>>> meaning_of_life = fourty_two()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fourty_two' is not defined
>>> meaning_of_life = lambda: fourty_two()
>>>
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#12
(Sep-09-2019, 06:17 AM)Skaperen Wrote: doing that for processes is harder. a mock itself would be so big it needs to go through its own testing.

If you'd bothered to read the link that ndc provided, you would find ways to do this without lots of testing. What Gerard Meszaros calls a 'stub', which just provides a canned answer, would solve your problem. You don't comment anything out, you provide a return value for any variable assignments, and it's so simple it doesn't need testing.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#13
i did read it. if i just change the answer, how does that prevent the call from going ahead and creating a new process?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#14
By having the mock function not create a new process. The mock function does nothing but return the value needed by the rest of the program. That's why it's called a 'stub.'
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#15
I think using Mock is a good approach.
For example you have some dangerous function, which is doing something and then should return something.
If your program relay on the return value, you can Mock the function to get the return prevent something happening in the background.

Example:

def delete_temp():
    """
    Example-Function to delete something
    """
    print('Deleting everything... oh nooooo')
    try:
        shutil.rmtree('/qwertzuiop')
    except Exception as e:
        print(e)
        return False
    return True
Instead of deleting the name of the function or changing the function, you can mock it.
from unittests.mock import Mock


class Delete_Temp(Mock):
    def __call__(self):
        return True


delete_temp = Delete_Temp()
print(delete_temp())
Then you can do also crazy things like:
>>> delete_temp.my_mock.is_super()
True
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#16
Note that using a mock doesn't necessarily imply using a mocking library. It can be easy enough to write your own. The basic idea is this: the thing you use in your production code has a particular interface (i.e. methods you can call on it with their defined signatures, set of possible return values and exceptions they can throw) and then a mock is simply another implementation of the same interface but one that's totally under your control.

Let's say I have a function to display some kind of rate (a tax rate or whatever else) and that rate is different in the morning and afternoon. I want to test that the correct string is output. I might write a test like:

import unittest
from display_rate import display_rate

class MockOutputStream(object):
    written = ""

    @staticmethod
    def write(value):
        MockOutputStream.written += value
        MockOutputStream.written += "\n"

class TestDisplayRate(unittest.TestCase):
    def test_morning_rate_is_displayed(self):
        hour_of_day = 6

        display_rate(hour_of_day, MockOutputStream.write)

        self.assertEquals(MockOutputStream.written, "The morning rate is 5%\n")


if __name__ == '__main__':
    unittest.main()
where the implementation might look like

def display_rate(hour_of_day, write):
    if hour_of_day < 12:
        rate = 5
        when = "morning"
    else:
        rate = 8
        when = "afternoon"

    write("The {} rate is {}%".format(when, rate))
The second argument to display_rate is a function for writing the output somewhere - in the test, it just writes to a variable called written in MockOutputStream and in production code, I might pass the print function so that output is written to standard out. They both conform to the same interface (a function that takes a value and returns None).

In the last couple days at work, two of us ended up writing our own simple mock in Lua. We aren't Lua experts on my team (we're a Scala team), but we needed to write in Lua because that's the language you can program in for NGINX. We do TDD and so wanted to write a test for a component we needed to implement that had to make a call to a remote service and return a value depending on the response. So, our unit tests just used a mocked version of the client so that we could test all our cases (success and various failures) and it was very lightweight - no need to go to the effort of figuring out how to use a library and it wouldn't have given us any real advantage even if we had.
Reply
#17
so how would the mock be looking like a process was created when it didn't create one?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#18
I guess you're missing the point: focus on the interface, not the implementation. You haven't really shown much code, so what does the interface to the dangerous operation look like? Is it a function? Is it a class? What methods are on it and what do they need to return?
Reply
#19
it is a function. that function constructs a command with information given in the function call arguments (AWS region name) and global reference settings (command path) then calls subprocess.Popen with it. it returns the value Popen() returned. the caller does this for every region given on the command line or, if none were given, for every known region. a mistake in the function, a typo, cause it to pick up all known regions instead of the one that was being passed by the caller. the command it was giving to Popen() was the script itself. the intention was to not launch a process at all if only one region was given. but that condition failed to be created resulting in thousands of processes and a system crash.

having the function not call Popen() would mean something would need to output mocked results that other code would be expecting to get over a pipe per child. if there is no child, then either something has to produce fake data to test the code that reads the results.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  compiling with an undefined variable Skaperen 0 977 Nov-10-2022, 11:59 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020