Created
June 15, 2013 15:56
-
-
Save fcasco/5788558 to your computer and use it in GitHub Desktop.
Context manager to avoid running a task twice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import unittest | |
class Avoid_twice(): | |
tasks_filename = '/tmp/avoid_twice' | |
def __init__(self, task_name): | |
self.current_task = task_name | |
def __enter__(self): | |
with open(self.tasks_filename) as i: | |
return self.current_task in i.read() | |
def __exit__(self, exc_type, exc_value, traceback): | |
if exc_type is None: | |
with open(self.tasks_filename, 'a') as o: | |
o.write(self.current_task + '\n') | |
class AvoidTwiceTestCases(unittest.TestCase): | |
def test_once(self): | |
l = [] | |
with Avoid_twice('task_name') as done: | |
if not done: | |
l.append(42) | |
with Avoid_twice('task_name') as done: | |
if not done: | |
l.append(42) | |
self.assertEqual(l, [42]) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment