unittest.TestCase
'a çok benzer bir şekilde çalışan bir Python akış denetimi çerçevesi yazdım: kullanıcı, framework sınıfından türetilen bir sınıf oluşturur ve sonra özel task_*(self)
yöntemlerini yazar. Çerçeve onları keşfeder ve onları çalıştırır:Yöntemi çağırmadan önce dekore edildiyse algıla.
###################
# FRAMEWORK LIBRARY
###################
import functools
class SkipTask(BaseException):
pass
def skip_if(condition):
def decorator(task):
@functools.wraps(task)
def wrapper(self, *args, **kargs):
if condition(self):
raise SkipTask()
return task(self, *args, **kargs)
return wrapper
return decorator
class MyFramework(object):
def run(self):
print "Starting task"
try:
self.task()
except SkipTask:
print "Skipped task"
except Exception:
print "Failed task"
raise
else:
print "Finished task"
#############
# USER SCRIPT
#############
class MyUserClass(MyFramework):
skip_flag = True
@skip_if(lambda self: self.skip_flag)
def task(self):
print "Doing something"
if __name__ == '__main__':
MyUserClass().run()
Çıktı: @skip_if
durumu True
olduğunda
Starting task
Skipped task
ben böylece çerçeveyi değiştirmek istiyorum, sarıcı "Starting task"
yazdırmaz. Bunu denedim, ama çalışmıyor:
def skip_if(condition):
def decorator(task):
print "decorating " + str(task)
task.__skip_condition = condition
return task
return decorator
class MyFramework(object):
def run(self):
try:
if self.task.__skip_condition():
print "Skipped task"
return
except AttributeError:
print str(self.task) + " is not decorated"
pass
print "Starting task"
try:
self.task()
except Exception as e:
print "Failed task: " + str(e)
raise
else:
print "Finished task"
:
decorating <function task at 0x194fcd70>
<bound method MyUserClass.task of <__main__.MyUserClass object at 0x195010d0>> is not decorated
Starting task
Doing something
Finished task
Neden görev yerine atlandı edilmedi?
Eğer daha açık olabilir misin: çıktı olur Bu değişikliklerle
* “işe yaramıyor” * - ne olmasını bekliyordunuz? – jonrsharpe
@jonrsharpe: çıktı testin atlandığını göstermelidir; bunun yerine çalışır. –