Ϫf `dZddlZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z mZmZmZmZmZmZmZmZmZmZmZddlmZddlmZddl mZddlmZmZdd l m!Z!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'm(Z(dd l)m*Z*dd l+m,Z,dd l-m.Z.m/Z/edZ0edZ1Gdde2Z3eGddZ4dee5eeee6eee6fe5ffde4fdZ7GddZ8dZ9dZ:Gdde;Z<GddZ=Gdd Z>Gd!d"ej~Z@Gd#d$ZAeAZBGd%d&e@ZCy)'zP Things likely to be used by writers of unit tests. Maintainer: Jonathan Lange N)findlinestarts) AnyCallable Coroutine GeneratorIterableListNoReturnOptionalTupleTypeTypeVarUnion)SkipTest)frozen) ParamSpec)DeferredensureDeferred)failurelogmonkey)DEPRECATION_WARNING_FORMATgetDeprecationWarningStringgetVersionStringwarnAboutFunction)fullyQualifiedName)runWithWarningsSuppressed)itrialutil_PTceZdZdZy)FailTestzA Raised to indicate the current test has failed to pass. N__name__ __module__ __qualname____doc__9/usr/lib/python3/dist-packages/twisted/trial/_synctest.pyr#r#9sr*r#cNeZdZUdZeed<dZeee e ed<defdZ dZ y)Todoa Internal object used to mark a L{TestCase} as 'todo'. Tests marked 'todo' are reported differently in Trial L{TestResult}s. If todo'd tests fail, they do not fail the suite and the errors are reported in a separate category. If todo'd tests succeed, Trial L{TestResult}s will report an unexpected success. @ivar reason: A string explaining why the test is marked 'todo' @ivar errors: An iterable of exception types that the test is expected to raise. If one of these errors is raised by the test, it will be trapped. Raising any other kind of error will fail the test. If L{None} then all errors will be trapped. reasonNerrorsreturnc<d|jd|jdS)Nz r.r/selfs r+__repr__z Todo.__repr__Sst{{oXdkk_AFFr*ch|jy|jD]}|j|syy)z @param failure: A L{twisted.python.failure.Failure}. @return: C{True} if C{failure} is expected, C{False} otherwise. TF)r/check)r5rerrors r+expectedz Todo.expectedVs: ;; [[ Ew}}U# r*) r%r&r'r(str__annotations__r/r rr BaseExceptionr6r:r)r*r+r-r-?s:  K6:FHXd=12 3:G#G r*r-valuer0ct|tr t|St|tr(|\}}t|tr|g}n|}t||Sy)a Return a L{Todo} object built from C{value}. If C{value} is a string, return a Todo that expects any exception with C{value} as a reason. If C{value} is a tuple, the second element is used as the reason and the first element as the excepted error(s). @param value: A string or a tuple of C{(errors, reason)}, where C{errors} is either a single exception class or an iterable of exception classes. @return: A L{Todo} object. )r.r3N) isinstancer;r-tupletype)r>r/r.iterableErrorss r+makeTodorDdsT"%5!!% fd #=CHN#N6.99  r*ceZdZdZdZy)_Warninga] A L{_Warning} instance represents one warning emitted through the Python warning system (L{warnings}). This is used to insulate callers of L{_collectWarnings} from changes to the Python warnings system which might otherwise require changes to the warning objects that function passes to the observer object it accepts. @ivar message: The string which was passed as the message parameter to L{warnings.warn}. @ivar category: The L{Warning} subclass which was passed as the category parameter to L{warnings.warn}. @ivar filename: The name of the file containing the definition of the code object which was C{stacklevel} frames above the call to L{warnings.warn}, where C{stacklevel} is the value of the C{stacklevel} parameter passed to L{warnings.warn}. @ivar lineno: The source line associated with the active instruction of the code object object which was C{stacklevel} frames above the call to L{warnings.warn}, where C{stacklevel} is the value of the C{stacklevel} parameter passed to L{warnings.warn}. c<||_||_||_||_yNmessagecategoryfilenamelineno)r5rJrKrLrMs r+__init__z_Warning.__init__s      r*N)r%r&r'r(rNr)r*r+rFrFs 0r*rFctt|jD] }| d|_y#t$rYwxYw)z Disable the per-module cache for every module found in C{modules}, typically C{sys.modules}. @param modules: Dictionary of modules, typically sys.module dict N)listvalues__warningregistry__r=)modulesvs r+_setWarningRegistryToNonerUsG'.." # = (,%!   s + 77c`dfd }ttjtjdd}tj }tj d |t_||i|}|tjdd|t_|S#|tjdd|t_wxYw)aU Call C{f} with C{args} positional arguments and C{kwargs} keyword arguments and collect all warnings which are emitted as a result in a list. @param observeWarning: A callable which will be invoked with a L{_Warning} instance each time a warning is emitted. @return: The return value of C{f(*args, **kwargs)}. Ncdt|tsJtt||||yrH)r@WarningrFr;)rJrKrLrMfilelineobserveWarnings r+ showWarningz%_collectWarnings..showWarnings*'7+++xG h&IJr*always)NN)rUsysrSwarningsfilters showwarning simplefilter)r[fargskwargsr\ origFiltersorigShowresults` r+_collectWarningsrisKckk*""1%K##H (#(*D#F#)' M*'s B B-ceZdZdZy)UnsupportedTrialFeaturez?A feature of twisted.trial was used that pyunit cannot support.Nr$r)r*r+rkrksIr*rkcZeZdZdZdZdZdZdZdZdZ dZ d Z dd Z d Z d ZdZy )PyUnitResultAdapterz Wrap a C{TestResult} from the standard library's C{unittest} so that it supports the extended result types from Trial, and also supports L{twisted.python.failure.Failure}s being passed to L{addError} and L{addFailure}. c||_y)zM @param original: A C{TestResult} instance from C{unittest}. N)original)r5ros r+rNzPyUnitResultAdapter.__init__s ! r*c,tj|SrH)rexcInfoOrFailureToExcInfo)r5errs r+ _exc_infozPyUnitResultAdapter._exc_infos--c22r*c:|jj|yrH)ro startTestr5methods r+ruzPyUnitResultAdapter.startTests 'r*c:|jj|yrH)rostopTestrvs r+ryzPyUnitResultAdapter.stopTests v&r*cZ|jj||j|yrH)ro addFailurers)r5testfails r+r{zPyUnitResultAdapter.addFailures   t~~d';(-8__^]INF NN  /66&}5&&'') r*N)r%r&r'r(rNrrrr)r*r+rrs& 5 !%r*rceZdZdZddeedefdZdfd ZeZ eZ eZ dfd Z e Z e Ze ZddZeZdfd ZeZeZeZdd ZeZeZdd ZeZeZdd ZeZeZeZdd Z e Z!dd Z"e"Z#ddZ$e$Z%e$Z&e$Z'ddZ(e(Z)e(Z*ddZ+e+Z,ddZ-e-Z.ddZ/e/Z0dZ1e1Z2ddZ3e3Z4dZ5e5Z6de7e8e9e:e;e:fedZ?xZ@S) _Assertionsz Replaces many of the built-in TestCase assertions. In general, these assertions provide better error messages and are easier to use in callbacks. msgr0c$|j|)z Absolutely fail the test. Do not pass go, do not collect $200. @param msg: the message that will be displayed as the reason for the failure failureException)r5rs r+r}z_Assertions.failvs##C((r*c(t||||S)z Fail the test if C{condition} evaluates to True. @param condition: any object that defines __nonzero__ )super assertFalser5 conditionr __class__s r+rz_Assertions.assertFalses Is+r*c(t||||S)z Fail the test if C{condition} evaluates to False. @param condition: any object that defines __nonzero__ )r assertTruers r+rz_Assertions.assertTrues 9c*r*cTt||}|S|jfdS)a Fail the test unless calling the function C{f} with the given C{args} and C{kwargs} raises C{exception}. The failure will report the traceback and call stack of the unexpected exception. @param exception: exception type that is to be expected @param f: the function to call @return: If C{f} is L{None}, a context manager which will make an assertion about the exception raised from the suite it manages. If C{f} is not L{None}, the exception raised by C{f}. @raise self.failureException: Raised if the function call does not raise an exception or if it raises an exception of a different type. ciSrHr))rdrcresr+z*_Assertions.assertRaises..sq$'9&'9r*)rr)r5rrcrdrers ``` r+ assertRaisesz_Assertions.assertRaisess+"'tY7 9N9::r*c*t|||||S)z Fail the test if C{first} and C{second} are not equal. @param msg: A string describing the failure that's included in the exception. )r assertEqual)r5firstsecondrrs r+rz_Assertions.assertEquals E63/ r*cB||ur|j|xs|d||S)a Fail the test if C{first} is not C{second}. This is an obect-identity-equality test, not an object equality (i.e. C{__eq__}) test. @param msg: if msg is None, then the failure message will be '%r is not %r' % (first, second) z is not rr5rrrs r+assertIsz_Assertions.assertIss2  ''(M%(6*/MN N r*cB||ur|j|xs|d||S)a  Fail the test if C{first} is C{second}. This is an obect-identity-equality test, not an object equality (i.e. C{__eq__}) test. @param msg: if msg is None, then the failure message will be '%r is %r' % (first, second) z is rrs r+ assertIsNotz_Assertions.assertIsNots1 F?''(I%$vj/IJ J r*cD||k7s|j|xs|d||S)z Fail the test if C{first} == C{second}. @param msg: if msg is None, then the failure message will be '%r == %r' % (first, second)  == rrs r+assertNotEqualz_Assertions.assertNotEquals1''(I%$vj/IJ J r*cB||vr|j|xs|d||S)a Fail the test if C{containee} is not found in C{container}. @param containee: the value that should be in C{container} @param container: a sequence type, or in the case of a mapping type, will follow semantics of 'if key in dict.keys()' @param msg: if msg is None, then the failure message will be '%r not in %r' % (first, second) z not in rr5 containee containerrs r+assertInz_Assertions.assertIns3 I %''(T)hym/TU Ur*cB||vr|j|xs|d||S)a Fail the test if C{containee} is found in C{container}. @param containee: the value that should not be in C{container} @param container: a sequence type, or in the case of a mapping type, will follow semantics of 'if key in dict.keys()' @param msg: if msg is None, then the failure message will be '%r in %r' % (first, second) z in rrs r+ assertNotInz_Assertions.assertNotIns3  !''(P)d9-/PQ Qr*cft||z |dk(r|j|xs |d|d|d|S)a Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero. @note: decimal places (from zero) is usually not the same as significant digits (measured from the most significant digit). @note: included for compatibility with PyUnit test cases rr within  placesroundrr5rrplacesrdeltas r+assertNotAlmostEqualz _Assertions.assertNotAlmostEqualL % (A -''J%$vj 'J  r*cft||z |dk7r|j|xs |d|d|d|S)a Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero. @note: decimal places (from zero) is usually not the same as significant digits (measured from the most significant digit). @note: included for compatibility with PyUnit test cases rz != rrrrs r+assertAlmostEqualz_Assertions.assertAlmostEqual(rr*c\t||z |kDr|j|xs|d||S)z Fail if C{first} - C{second} > C{tolerance} @param msg: if msg is None, then the failure message will be '%r ~== %r' % (first, second) z ~== )absr)r5rr tolerancers r+assertApproximatesz_Assertions.assertApproximates=s; uv~  *''(F%fX/FG G r*c(|j|||S)zH Fail if C{substring} does not exist within C{astring}. ) failUnlessInr5 substringastringrs r+assertSubstringz_Assertions.assertSubstringJs  GS99r*c(|j|||S)z; Fail if C{astring} contains C{substring}. )failIfInrs r+assertNotSubstringz_Assertions.assertNotSubstringRs}}Y55r*cg}t|j|g|i|}|s|jd|d} |ddD]E} | j| jf| j| jfk7s5|jdG|j | j||j | j||j|j| jd| jd||S)a Fail if the given function doesn't generate the specified warning when called. It calls the function, checks the warning, and forwards the result of the function if everything is fine. @param category: the category of the warning to check. @param message: the output message of the warning to check. @param filename: the filename where the warning should come from. @param f: the function which is supposed to generate the warning. @type f: any callable. @param args: the arguments to C{f}. @param kwargs: the keywords arguments to C{f}. @return: the result of the original function C{f}. zNo warnings emittedrNzCan't handle different warningsz Warning in z , expected ) riappendr}rJrKrassertIdenticalr startswithrL) r5rKrJrLrcrdre warningsShownrhrothers r+ assertWarnsz_Assertions.assertWarnsZs  !-"6"6KDKFK II+ ,a "12& =E u~~.5==%..2QQ ;< = 0 U^^X6     /%..+;xl C  r*cbt||s#|d}nd|z}|j|d||yy)a Fail if C{instance} is not an instance of the given class or of one of the given classes. @param instance: the object to test the type (first argument of the C{isinstance} call). @type instance: any. @param classOrTuple: the class or classes to test against (second argument of the C{isinstance} call). @type classOrTuple: class, type, or tuple. @param message: Custom text to include in the exception text if the assertion fails. N: z is not an instance of r@r})r5instance classOrTuplerJsuffixs r+assertIsInstancez_Assertions.assertIsInstancesB(L1 II $;L>&R S 2r*cJt||r|j|d|yy)a Fail if C{instance} is an instance of the given class or of one of the given classes. @param instance: the object to test the type (first argument of the C{isinstance} call). @type instance: any. @param classOrTuple: the class or classes to test against (second argument of the C{isinstance} call). @type classOrTuple: class, type, or tuple. z is an instance of Nr)r5rrs r+assertNotIsInstancez_Assertions.assertNotIsInstances+ h - II $7 ~F G .r*deferredc6t|}g}|j|j|s |jdj ||d}t |t jr/|jdj ||j|S)a Return the current success result of C{deferred} or raise C{self.failureException}. @param deferred: A L{Deferred} or I{coroutine} which has a success result. For a L{Deferred} this means L{Deferred.callback} or L{Deferred.errback} has been called on it and it has reached the end of its callback chain and the last callback or errback returned a non-L{failure.Failure}. For a I{coroutine} this means all awaited values have a success result. @raise SynchronousTestCase.failureException: If the L{Deferred} has no result or has a failure result. @return: The result of C{deferred}. z8Success result expected on {!r}, found no result insteadrzASuccess result expected on {!r}, found failure result instead: {}) raddBothrr}rr@rrr)r5rresultsrhs r+successResultOfz_Assertions.successResultOfs>"(+35( IIJQQ   fgoo . II44:Ff1135   r*c Dt|}g}|j|j|s |jdj ||d}t |t js!|jdj |||r|j|sdj|Dcgc])}dj|j|jf+c}}|jdj |||j|j|Scc}w)a Return the current failure result of C{deferred} or raise C{self.failureException}. @param deferred: A L{Deferred} which has a failure result. This means L{Deferred.callback} or L{Deferred.errback} has been called on it and it has reached the end of its callback chain and the last callback or errback raised an exception or returned a L{failure.Failure}. @type deferred: L{Deferred} @param expectedExceptionTypes: Exception types to expect - if provided, and the exception wrapped by the failure result is not one of the types provided, then this test will fail. @raise SynchronousTestCase.failureException: If the L{Deferred} has no result, has a success result, or has an unexpected failure result. @return: The failure result of C{deferred}. @rtype: L{failure.Failure} z8Failure result expected on {!r}, found no result insteadrzDFailure result expected on {!r}, found success result ({!r}) insteadz or .zBFailure of type ({}) expected on {!r}, found type {!r} instead: {})rrrr}rr@rrr8joinr&r%rBr)r5rexpectedExceptionTypesrhtexpectedStrings r+failureResultOfz_Assertions.failureResultOfs2"(+' IIJQQ  &'//2 II66} without a result. This means that neither L{Deferred.callback} nor L{Deferred.errback} has been called, or that the L{Deferred} is waiting on another L{Deferred} for a result. @type deferred: L{Deferred} @raise SynchronousTestCase.failureException: If the L{Deferred} has a result. c*j||SrH)r)resrhs r+cbz&_Assertions.assertNoResult..cb4s MM# Jr*cyrHr))_s r+rz,_Assertions.assertNoResult..=r*z.No result expected on {!r}, found {!r} insteadrN)rr addErrbackr}r)r5rr rhs @r+assertNoResultz_Assertions.assertNoResultsd&"(+       / II@GGfQi  r*rH)NN)Ar%r&r'r(r objectr r}r assertNotfailUnlessFalsefailIfrassert_failUnlessTrue failUnlessrfailUnlessRaisesrfailUnlessEqualfailUnlessEquals assertEqualsrfailUnlessIdenticalrrfailIfIdenticalassertNotIdenticalrassertNotEquals failIfEquals failIfEqualrrrrrassertNotAlmostEqualsfailIfAlmostEqualfailIfAlmostEqualsrassertAlmostEqualsfailUnlessAlmostEqualrfailUnlessApproximatesrfailUnlessSubstringrfailIfSubstringrfailUnlessWarnsrfailUnlessIsInstancerfailIfIsInstancerrrr!rrrrr __classcell__rs@r+rros )()H)I!O FGNJ;4$"O"L #O "O$ %O!L K L H$1,-$+- 0: *6 )O(T"OT,, H+3 hqk3) * hqk3) * QK  3 3j8t$r*rc@eZdZdZdZdZdZdZdZdZ dZ d Z y ) _LogObservera Observes the Twisted logs and catches any errors. @ivar _errors: A C{list} of L{Failure} instances which were received as error events from the Twisted logging system. @ivar _added: A C{int} giving the number of times C{_add} has been called less the number of times C{_remove} has been called; used to only add this observer to the Twisted logging since once, regardless of the number of calls to the add method. @ivar _ignored: A C{list} of exception types which will not be recorded. c.g|_d|_g|_y)Nr)_errors_added_ignoredr4s r+rNz_LogObserver.__init__Ts   r*c|jdk(rtj|j|xjdz c_y)Nrr)r4r addObservergotEventr4s r+_addz_LogObserver._addYs, ;;!  OODMM * q r*c|xjdzc_|jdk(r tj|jyy)Nrr)r4rremoveObserverr8r4s r+_removez_LogObserver._remove^s3 q ;;!    t}} - r*c:|jj|y)zF Do not store any errors with any of the given types. N)r5extendr5 errorTypess r+ _ignoreErrorsz_LogObserver._ignoreErrorscs Z(r*cg|_y)zJ Stop ignoring any errors we might currently be ignoring. N)r5r4s r+ _clearIgnoresz_LogObserver._clearIgnoresis  r*c|rPg}g}|jD]4}|j|r|j|$|j|6||_|S|j}g|_|S)z Flush errors from the list of caught errors. If no arguments are specified, remove all errors. If arguments are specified, only remove errors of those types from the stored list. )r3r8r)r5r@flushed remainderrcs r+ flushErrorsz_LogObserver.flushErrorsoss GI\\ (177J'NN1%$$Q'  ( %DLllGDLr*c|jS)zB Return a list of errors caught by this observer. )r3r4s r+ getErrorsz_LogObserver.getErrorss||r*c|jddrXd|vrS|d}t|jdk(s|j|js|jj |yyyy)z The actual observer method. Called whenever a message is logged. @param event: A dictionary containing the log message. Actual structure undocumented (see source for L{twisted.python.log}). isErrorFrrN)getlenr5r8r3r)r5eventrcs r+r8z_LogObserver.gotEventse 99Y &9+=i A4==!Q&gaggt}}.E ##A&/F,> &r*N) r%r&r'r(rNr9r<rArCrGrIr8r)r*r+r1r1Es/   . )  ( 'r*r1ceZdZdZeZdfd ZdedefdZ dZ fdZ de ee effdZd Zd Zd Zd eeefd ej*dej,ddfdZdZdZddZddZdZdZdZdZdZ dZ!dZ"dZ#dZ$xZ%S) SynchronousTestCasea  A unit test. The atom of the unit testing universe. This class extends C{unittest.TestCase} from the standard library. A number of convenient testing helpers are added, including logging and warning integration, monkey-patching support, and more. To write a unit test, subclass C{SynchronousTestCase} and define a method (say, 'test_foo') on the subclass. To run the test, instantiate your subclass with the name of the method, and call L{run} on the instance, passing a L{TestResult} object. The C{trial} script will automatically find any C{SynchronousTestCase} subclasses defined in modules beginning with 'test_' and construct test cases for all methods beginning with 'test'. If an error is logged during the test run, the test will fail with an error. See L{log.err}. @ivar failureException: An exception class, defaulting to C{FailTest}. If the test method raises this exception, it will be reported as a failure, rather than an exception. All of the assertion methods raise this if the assertion fails. @ivar skip: L{None} or a string explaining why this test is to be skipped. If defined, the test will not be run. Instead, it will be reported to the result object as 'skipped' (if the C{TestResult} supports skipping). @ivar todo: L{None}, a string or a tuple of C{(errors, reason)} where C{errors} is either an exception class or an iterable of exception classes, and C{reason} is a string. See L{Todo} or L{makeTodo} for more information. @ivar suppress: L{None} or a list of tuples of C{(args, kwargs)} to be passed to C{warnings.filterwarnings}. Use these to suppress warnings raised in a test. Useful for testing deprecated code. See also L{util.suppress}. ct||d|_g|_||_t ||}||t jj|jjg|_ y)NF) rrN_passed _cleanups_testMethodNamegetattrr^rSrLrr&_parents)r5 methodName testMethodrs r+rNzSynchronousTestCase.__init__sW $ )T:. #T3;;??4>>;T;T+UV r*rr0c6t|tr||uStS)a Override the comparison defined by the base TestCase which considers instances of the same class with the same _testMethodName to be equal. Since trial puts TestCase instances into a set, that definition of comparison makes it impossible to run the same test method twice. Most likely, trial should stop using a set to hold tests, but until it does, this is necessary on Python 2.6. -exarkun )r@rPNotImplemented)r5rs r+__eq__zSynchronousTestCase.__eq__s e0 15= ! !r*cDt|j|jfSrH)hashrrTr4s r+__hash__zSynchronousTestCase.__hash__sT^^T%9%9:;;r*c@t|}| |jS|SrH)rshortDescriptionrT)r5descrs r+r`z$SynchronousTestCase.shortDescriptions&w') <'' ' r*ctj|jdd}|du}|t|dd}|r t|dd}||fS)aN Return the skip reason set on this test, if any is set. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a C{skip} attribute, returns that in a tuple (L{True}, L{str}). If the C{skip} attribute does not exist, look for C{__unittest_skip__} and C{__unittest_skip_why__} attributes which are set by the standard library L{unittest.skip} function. Returns (L{False}, L{None}) if it cannot find anything. See L{TestCase} docstring for more details. skipN__unittest_skip__F__unittest_skip_why__r)racquireAttributerVrU)r5 skipReasondoSkips r+getSkipzSynchronousTestCase.getSkipsX**4==&$G 4'  T#6>F$T+BBG  ##r*c`tj|jdd}|yt|S)aQ Return a L{Todo} object if the test is marked todo. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a C{todo} attribute, returns that. Returns L{None} if it cannot find anything. See L{TestCase} docstring for more details. rN)rrfrVrD)r5rs r+getTodozSynchronousTestCase.getTodos.$$T]]FDA <~r*cy)z If no C{methodName} argument is passed to the constructor, L{run} will treat this method as the thing with the actual test inside. Nr)r4s r+runTestzSynchronousTestCase.runTestrr*ctjd|jztj|d}| t |}n|}|j ||j\}}|r$|j|||j|yd|_ g|_ |jt|jj|j||j!D]} t#j$di||j|y#t&$r'|j)|t+j,Y\wxYw)a Run the test case, storing the results in C{result}. First runs C{setUp} on self, then runs the test method (defined in the constructor), then runs C{tearDown}. As with the standard library L{unittest.TestCase}, the return value of these methods is disregarded. In particular, returning a L{Deferred} has no special additional consequences. @param result: A L{TestResult} object. z --> %s <--NFr))rridr IReporterrmrurirryrR _warnings_installObserverrir_runFixturesAndTest flushWarningsr_ warn_explicitr=rrr)r5rh new_resultrhrgws r+runzSynchronousTestCase.run s   *+%%fd3  (0FF#||~  NN4 , OOD !    ..0H0H&Q##% 9A 9&&++ 9 ! 9goo&78 9s4D-E  E rcrdreNc@|jj|||fy)as Add the given function to a list of functions to be called after the test has run, but before C{tearDown}. Functions will be run in reverse order of being added. This helps ensure that tear down complements set up. As with all aspects of L{SynchronousTestCase}, Deferreds are not supported in cleanup functions. N)rSr)r5rcrdres r+ addCleanupzSynchronousTestCase.addCleanup7s q$/0r*ctj|||f}|j|j|j|S)a Monkey patch an object for the duration of the test. The monkey patch will be reverted at the end of the test using the L{addCleanup} mechanism. The L{monkey.MonkeyPatcher} is returned so that users can restore and re-apply the monkey patch within their tests. @param obj: The object to monkey patch. @param attribute: The name of the attribute to change. @param value: The value to set the attribute to. @return: A L{monkey.MonkeyPatcher} object. )r MonkeyPatcherpatchrzrestore)r5r attributer> monkeyPatchs r+r}zSynchronousTestCase.patchFs?**CE+BC   ++,r*c4|jj|S)a Remove stored errors received from the log. C{TestCase} stores each error logged during the run of the test and reports them as errors during the cleanup phase (after C{tearDown}). @param errorTypes: If unspecified, flush all errors. Otherwise, only flush errors that match the given types. @return: A list of failures that have been removed. ) _observerrGr?s r+flushLoggedErrorsz%SynchronousTestCase.flushLoggedErrorsZs*t~~)):66r*cZ| |jdd}g|jddnBg}|jD]}|D]}t|tjtjfst |dt j|j}tj|}|tjj|jk7rt|j Dcgc] \}}|| } }}t#| |j$cxkrt'| ksn|j)| t+t-|jj.||D cgc]1} | j0| j2| j| j$d3c} Scc}}wcc} w)a Remove stored warnings from the list of captured warnings and return them. @param offendingFunctions: If L{None}, all warnings issued during the currently running test will be flushed. Otherwise, only warnings which I{point} to a function included in this list will be flushed. All warnings include a filename and source line number; if these parts of a warning point to a source line which is part of a function, then the warning I{points} to that function. @type offendingFunctions: L{None} or L{list} of functions or methods. @raise ValueError: If C{offendingFunctions} is not L{None} and includes an object which is not a L{types.FunctionType} or L{types.MethodType} instance. @return: A C{list}, each element of which is a C{dict} giving information about one warning which was flushed by this call. The keys of each C{dict} are: - C{'message'}: The string which was passed as the I{message} parameter to L{warnings.warn}. - C{'category'}: The warning subclass which was passed as the I{category} parameter to L{warnings.warn}. - C{'filename'}: The name of the file containing the definition of the code object which was C{stacklevel} frames above the call to L{warnings.warn}, where C{stacklevel} is the value of the C{stacklevel} parameter passed to L{warnings.warn}. - C{'lineno'}: The source line associated with the active instruction of the code object object which was C{stacklevel} frames above the call to L{warnings.warn}, where C{stacklevel} is the value of the C{stacklevel} parameter passed to L{warnings.warn}. Nz is not a function or methodrI)rqr@types FunctionType MethodType ValueErrorr^rSr&inspect getabsfileospathnormcaserL_findlinestarts__code__minrMmaxrrPmapremoverJrK) r5offendingFunctionstoFlushaWarning aFunctionaModulerLr  lineNumber lineNumbersrws r+rtz!SynchronousTestCase.flushWarningshsL  %nnQ'G "DNN1 G NN# !3"I%!E$6$68H8H#I)I=8T)UVV"kk)*>*>?G&11':H277#3#3H4E4E#FF .=Y=O=O-P#)Az%1##K#  ,S3{CSS NN8,E"# J T^^**G4 5  99JJJJ((    # s )F" )6F(cl|dz|z}tj|}t||}|j|jg}t |dk(r|j |d|dd} t|t|dz} || dz|z} |j| j| d| d| |S) a Retrieve a module attribute which should have been deprecated, and assert that we saw the appropriate deprecation warning. @type moduleName: C{str} @param moduleName: Fully-qualified Python name of the module containing the deprecated attribute; if called from the same module as the attributes are being deprecated in, using the C{__name__} global can be helpful @type name: C{str} @param name: Attribute name which we expect to be deprecated @param version: The first L{version} that the module attribute was deprecated. @type message: C{str} @param message: (optional) The expected deprecation message for the module attribute @return: The given attribute from the named module @raise FailTest: if no warnings were emitted on getattr, or if the L{DeprecationWarning} emitted did not produce the canonical please-use-something-else message that is standard for Twisted deprecations according to the given version and replacement. @since: Twisted 21.2.0 rr is not deprecated.rJ)fqpnversionrz Expected z to start with ) r^rSrUrtgetDeprecatedModuleAttributerMr}rrrr) r5 moduleNamenamerrJrmoduleattrrobservedWarningexpectedWarnings r+rz0SynchronousTestCase.getDeprecatedModuleAttributes:C$&Z(vt$**D,M,M+NO }  " II12 3'*954'08    -4w>O  & & 7*//9L M  r*c*||i|}|j|jg} t|}|\}} t |dk(r|j |d|dd} t ||| } |j| | |S#t$r|}d} Y[wxYw)aM Call a function that should have been deprecated at a specific version and in favor of a specific alternative, and assert that it was thusly deprecated. @param version: A 2-sequence of (since, replacement), where C{since} is a the first L{version} that C{f} should have been deprecated since, and C{replacement} is a suggested replacement for the deprecated functionality, as described by L{twisted.python.deprecate.deprecated}. If there is no suggested replacement, this parameter may also be simply a L{version} by itself. @param f: The deprecated function to call. @param args: The arguments to pass to C{f}. @param kwargs: The keyword arguments to pass to C{f}. @return: Whatever C{f} returns. @raise Exception: Whatever C{f} raises. If any exception is raised by C{f}, though, no assertions will be made about emitted deprecations. @raise FailTest: if no warnings were emitted by C{f}, or if the L{DeprecationWarning} emitted did not produce the canonical please-use-something-else message that is standard for Twisted deprecations according to the given version and replacement. NrrrJ) replacement)rtcallDeprecatedrP TypeErrorrMr}rr) r5rrcrdrerhrrsincerrrs r+rz"SynchronousTestCase.callDeprecateds>D#F#**D,?,?+@A  (=D $( UK }  " II01 2'*955aKX /:  EK s B BBcd}tjj|jjd||jj d||j d|}tjj|stj|tjjtjdd|}tjj|dS)a Create a new path name which can be used for a new file or directory. The result is a relative path that is guaranteed to be unique within the current working directory. The parent of the path will exist, but the path will not. For a temporary directory call os.mkdir on the path. For a temporary file just create the file (e.g. by opening the path for writing and then closing it). @return: The newly created path @rtype: C{str} Nrtemp) rrrrr&r%rTexistsmakedirsrelpathtempfilemkdtemp)r5 MAX_FILENAMEbasedirnames r+mktempzSynchronousTestCase.mktemp(s ww|| NN % %m| 4 NN # #M\ 2  , /  ww~~d# KK  ''//("2"22r4"@Aww||GV,,r*cDtj|jdgS)ax Returns any warning suppressions set for this test. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a C{suppress} attribute, returns that. Returns any empty list (i.e. suppress no warnings) if it cannot find anything. See L{TestCase} docstring for more details. suppress)rrfrVr4s r+ _getSuppressz SynchronousTestCase._getSuppressFs$$T]]JCCr*clt|jdkDr|jdSt|d|S)z Return the reason to use for skipping a test method. @param method: The method which produced the skip. @param skip: A L{unittest.SkipTest} instance raised by C{method}. rzSDo not raise unittest.SkipTest with no arguments! Give a reason for skipping tests!)rMrdr)r5rwrcs r+_getSkipReasonz"SynchronousTestCase._getSkipReasonPs9 tyy>A 99Q<   "  r*c>tj|r@tdj|}|j |t j |y t||y#t$r,}|j||j||Yd}~yd}~wt$r|t j }||j|s?|j|jr |j}n |j}|||Yy|j!|||YywxYw)a Run a single method, either a test method or fixture. @param suppress: Any warnings to suppress, as defined by the C{suppress} attribute on this method, test case, or the module it is defined in. @param todo: Any expected failure or failures, as defined by the C{todo} attribute on this method, test case, or the module it is defined in. @param method: The method to run. @param result: The TestResult instance to which to report results. @return: C{True} if the method fails and no further method/fixture calls should be made, C{False} otherwise. z9{!r} is a generator function and therefore will never runTFN)risgeneratorfunctionrrrrrrrrrr=r:r8rr{r) r5rrrwrhexcer. addResults r+_runzSynchronousTestCase._runas"  & &v .KRRC OOD'//#"6 7  %h 7 A NN4!4!4VQ!? @ @ >__&F|4==#8<< 5 56 & 1 1I &I$' ))$= >s% A$$ D-"BA0DDDc|j} |j|d|j|r |j|y|j }t ||j }|j||||}|j||r|s|j|||j|d|j|rd}|jjD]}|j||d}|jj|j|s|s|j|yyy#|j|wxYw)z Run C{setUp}, a test method, test cleanups, and C{tearDown}. @param result: The TestResult instance to which to report results. NT)rrsetUp _runCleanupsrkrUrTrtearDownrrIrrG_removeObserverr)r5rhrrrwfailedr9s r+rsz'SynchronousTestCase._runFixturesAndTests* $$& &yy4V<   f % <<>DT4#7#78FYYxvv>F   f %   ' 'd 3 99XtT]]F ;F^^--/ E OOD% (F  ""$ $   d #   f %sD9:D99E c t|jdkDrA|jj\}}} ||i|t|jdkDr@yy#t$r)t j }|j ||YLwxYw)zG Synchronously run any cleanups which have been added. rN)rMrSpopr=rrr)r5rhrcrdres r+rz SynchronousTestCase._runCleanupss}$..!A%"nn002OAtV )4"6"$..!A%! )OO%a( )sA/B  B cNt|_|jjyrH) _logObserverrr9r4s r+rrz$SynchronousTestCase._installObservers% r*c8|jjyrH)rr<r4s r+rz#SynchronousTestCase._removeObservers  r*)rmrH)&r%r&r'r(r#rrNrboolr[r^r`r r r;rirkrmrxrr rdrerzr}rrtrrrrrrrsrrrrr.r/s@r+rPrPs&P W "F "t "< $tXc]23$(  )Z 1"f*% 1.0gg 1AC 1  1( 7Z x0d0d-<D")V$@ )!r*rP)Dr(rrr^rrunittestpyunitr_disrrtypingrrrrrr r r r r rrrattrsrrtwisted.internet.deferrrtwisted.pythonrrrtwisted.python.deprecaterrrrtwisted.python.reflectrtwisted.python.utilr twisted.trialrrr r!AssertionErrorr#r-r;r=rDrFrUri ExceptionrkrmrTestCaserr1rrPr)r*r+rsS   1     ;// 69&t_ CL~ !!!H:  U5m,htM7J.KKLcQ RR : :8@$@JiJ9 9 xZZzS&//SlN'N'b~ d!+d!r*