File: test_twisted.py

package info (click to toggle)
python-eliot 1.16.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 964 kB
  • sloc: python: 8,641; makefile: 151
file content (814 lines) | stat: -rw-r--r-- 25,484 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
"""
Tests for L{eliot.twisted}.
"""

import sys
from functools import wraps

try:
    from twisted.internet.defer import Deferred, succeed, fail, returnValue
    from twisted.trial.unittest import TestCase
    from twisted.python.failure import Failure
    from twisted.logger import globalLogPublisher
except ImportError:
    # Make tests not run at all.
    TestCase = object
else:
    # Make sure we always import this if Twisted is available, so broken
    # logwriter.py causes a failure:
    from ..twisted import (
        DeferredContext,
        AlreadyFinished,
        _passthrough,
        redirectLogsForTrial,
        _RedirectLogsForTrial,
        TwistedDestination,
        inline_callbacks,
    )

from .test_generators import assert_expected_action_tree

from .._action import start_action, current_action, Action, TaskLevel
from .._output import MemoryLogger, Logger
from .._message import Message
from ..testing import assertContainsFields, capture_logging
from .. import removeDestination, addDestination
from .._traceback import write_traceback
from .common import FakeSys


class PassthroughTests(TestCase):
    """
    Tests for L{_passthrough}.
    """

    def test_passthrough(self):
        """
        L{_passthrough} returns the passed-in value.
        """
        obj = object()
        self.assertIs(obj, _passthrough(obj))


def withActionContext(f):
    """
    Decorator that calls a function with an action context.

    @param f: A function.
    """
    logger = MemoryLogger()
    action = start_action(logger, "test")

    @wraps(f)
    def test(self):
        with action.context():
            return f(self)

    return test


class DeferredContextTests(TestCase):
    """
    Tests for L{DeferredContext}.
    """

    def test_requireContext(self):
        """
        L{DeferredContext} raises a L{RuntimeError} if it is called without an
        action context.
        """
        self.assertRaises(RuntimeError, DeferredContext, Deferred())

    @withActionContext
    def test_result(self):
        """
        The passed-in L{Deferred} is available as the L{DeferredContext}'s
        C{result} attribute.
        """
        result = Deferred()
        context = DeferredContext(result)
        self.assertIs(context.result, result)

    @withActionContext
    def test_addCallbacksCallbackToDeferred(self):
        """
        L{DeferredContext.addCallbacks} passes the given callback and its
        corresponding arguments to the wrapped L{Deferred}'s
        C{addCallbacks}.
        """
        called = []

        def f(value, x, y):
            called.append((value, x, y))

        result = Deferred()
        context = DeferredContext(result)
        context.addCallbacks(f, lambda x: None, (1,), {"y": 2})
        result.callback(0)
        self.assertEqual(called, [(0, 1, 2)])

    @withActionContext
    def test_addCallbacksErrbackToDeferred(self):
        """
        L{DeferredContext.addCallbacks} passes the given errback and its
        corresponding arguments to the wrapped L{Deferred}'s
        C{addCallbacks}.
        """
        called = []

        def f(value, x, y):
            value.trap(RuntimeError)
            called.append((x, y))

        result = Deferred()
        context = DeferredContext(result)
        context.addCallbacks(lambda x: None, f, None, None, (1,), {"y": 2})
        result.errback(RuntimeError())
        self.assertEqual(called, [(1, 2)])

    @withActionContext
    def test_addCallbacksWithOnlyCallback(self):
        """
        L{DeferredContext.addCallbacks} can be called with a single argument, a
        callback function, and passes it to the wrapped L{Deferred}'s
        C{addCallbacks}.
        """
        called = []

        def f(value):
            called.append(value)

        result = Deferred()
        context = DeferredContext(result)
        context.addCallbacks(f)
        result.callback(0)
        self.assertEqual(called, [0])

    @withActionContext
    def test_addCallbacksWithOnlyCallbackErrorCase(self):
        """
        L{DeferredContext.addCallbacks} can be called with a single argument, a
        callback function, and passes a pass-through errback to the wrapped
        L{Deferred}'s C{addCallbacks}.
        """
        called = []

        def f(value):
            called.append(value)

        class ExpectedException(Exception):
            pass

        result = Deferred()
        context = DeferredContext(result)
        context.addCallbacks(f)
        result.errback(Failure(ExpectedException()))
        self.assertEqual(called, [])
        # The assertion is inside `failureResultOf`.
        self.failureResultOf(result, ExpectedException)

    @withActionContext
    def test_addCallbacksReturnSelf(self):
        """
        L{DeferredContext.addCallbacks} returns the L{DeferredContext}.
        """
        result = Deferred()
        context = DeferredContext(result)
        self.assertIs(context, context.addCallbacks(lambda x: None, lambda x: None))

    def test_addCallbacksCallbackContext(self):
        """
        L{DeferedContext.addCallbacks} adds a callback that runs in context of
        action that the L{DeferredContext} was created with.
        """
        logger = MemoryLogger()
        action1 = start_action(logger, "test")
        action2 = start_action(logger, "test")
        context = []
        d = succeed(None)
        with action1.context():
            d = DeferredContext(d)
            with action2.context():
                d.addCallbacks(lambda x: context.append(current_action()), lambda x: x)
        self.assertEqual(context, [action1])

    def test_addCallbacksErrbackContext(self):
        """
        L{DeferedContext.addCallbacks} adds an errback that runs in context of
        action that the L{DeferredContext} was created with.
        """
        logger = MemoryLogger()
        action1 = start_action(logger, "test")
        action2 = start_action(logger, "test")
        context = []
        d = fail(RuntimeError())
        with action1.context():
            d = DeferredContext(d)
            with action2.context():
                d.addCallbacks(lambda x: x, lambda x: context.append(current_action()))
        self.assertEqual(context, [action1])

    @withActionContext
    def test_addCallbacksCallbackResult(self):
        """
        A callback added with DeferredContext.addCallbacks has its result
        passed on to the next callback.
        """
        d = succeed(0)
        d = DeferredContext(d)
        d.addCallbacks(lambda x: [x, 1], lambda x: x)
        self.assertEqual(self.successResultOf(d.result), [0, 1])

    @withActionContext
    def test_addCallbacksErrbackResult(self):
        """
        An errback added with DeferredContext.addCallbacks has its result
        passed on to the next callback.
        """
        exception = ZeroDivisionError()
        d = fail(exception)
        d = DeferredContext(d)
        d.addCallbacks(lambda x: x, lambda x: [x.value, 1])
        self.assertEqual(self.successResultOf(d.result), [exception, 1])

    def test_addActionFinishNoImmediateLogging(self):
        """
        L{DeferredContext.addActionFinish} does not log anything if the
        L{Deferred} hasn't fired yet.
        """
        d = Deferred()
        logger = MemoryLogger()
        action = Action(logger, "uuid", TaskLevel(level=[1]), "sys:me")
        with action.context():
            DeferredContext(d).addActionFinish()
        self.assertFalse(logger.messages)

    def test_addActionFinishSuccess(self):
        """
        When the L{Deferred} referred to by L{DeferredContext.addActionFinish}
        fires successfully, a finish message is logged.
        """
        d = Deferred()
        logger = MemoryLogger()
        action = Action(logger, "uuid", TaskLevel(level=[1]), "sys:me")
        with action.context():
            DeferredContext(d).addActionFinish()
        d.callback("result")
        assertContainsFields(
            self,
            logger.messages[0],
            {
                "task_uuid": "uuid",
                "task_level": [1, 1],
                "action_type": "sys:me",
                "action_status": "succeeded",
            },
        )

    def test_addActionFinishSuccessPassThrough(self):
        """
        L{DeferredContext.addActionFinish} passes through a successful result
        unchanged.
        """
        d = Deferred()
        logger = MemoryLogger()
        action = Action(logger, "uuid", TaskLevel(level=[1]), "sys:me")
        with action.context():
            DeferredContext(d).addActionFinish()
        d.callback("result")
        result = []
        d.addCallback(result.append)
        self.assertEqual(result, ["result"])

    def test_addActionFinishFailure(self):
        """
        When the L{Deferred} referred to in L{DeferredContext.addActionFinish}
        fires with an exception, a finish message is logged.
        """
        d = Deferred()
        logger = MemoryLogger()
        action = Action(logger, "uuid", TaskLevel(level=[1]), "sys:me")
        with action.context():
            DeferredContext(d).addActionFinish()
        exception = RuntimeError("because")
        d.errback(exception)
        assertContainsFields(
            self,
            logger.messages[0],
            {
                "task_uuid": "uuid",
                "task_level": [1, 1],
                "action_type": "sys:me",
                "action_status": "failed",
                "reason": "because",
                "exception": "%s.RuntimeError" % (RuntimeError.__module__,),
            },
        )
        d.addErrback(lambda _: None)  # don't let Failure go to Twisted logs

    def test_addActionFinishFailurePassThrough(self):
        """
        L{DeferredContext.addActionFinish} passes through a failed result
        unchanged.
        """
        d = Deferred()
        logger = MemoryLogger()
        action = Action(logger, "uuid", TaskLevel(level=[1]), "sys:me")
        with action.context():
            DeferredContext(d).addActionFinish()
        failure = Failure(RuntimeError())
        d.errback(failure)
        result = []
        d.addErrback(result.append)
        self.assertEqual(result, [failure])

    @withActionContext
    def test_addActionFinishRaisesAfterAddActionFinish(self):
        """
        After L{DeferredContext.addActionFinish} is called, additional calls to
        L{DeferredContext.addActionFinish} result in a L{AlreadyFinished}
        exception.
        """
        d = DeferredContext(Deferred())
        d.addActionFinish()
        self.assertRaises(AlreadyFinished, d.addActionFinish)

    @withActionContext
    def test_addCallbacksRaisesAfterAddActionFinish(self):
        """
        After L{DeferredContext.addActionFinish} is called, additional calls to
        L{DeferredContext.addCallbacks} result in a L{AlreadyFinished}
        exception.
        """
        d = DeferredContext(Deferred())
        d.addActionFinish()
        self.assertRaises(AlreadyFinished, d.addCallbacks, lambda x: x, lambda x: x)

    @withActionContext
    def test_addActionFinishResult(self):
        """
        L{DeferredContext.addActionFinish} returns the L{Deferred}.
        """
        d = Deferred()
        self.assertIs(d, DeferredContext(d).addActionFinish())

    # Having made sure DeferredContext.addCallbacks does the right thing
    # regarding action contexts, for addCallback/addErrback/addBoth we only
    # need to ensure that they call DeferredContext.addCallbacks.

    @withActionContext
    def test_addCallbackCallsAddCallbacks(self):
        """
        L{DeferredContext.addCallback} passes its arguments on to
        L{DeferredContext.addCallbacks}.
        """
        result = Deferred()
        context = DeferredContext(result)
        called = []

        def addCallbacks(
            callback,
            errback,
            callbackArgs=None,
            callbackKeywords=None,
            errbackArgs=None,
            errbackKeywords=None,
        ):
            called.append(
                (
                    callback,
                    errback,
                    callbackArgs,
                    callbackKeywords,
                    errbackArgs,
                    errbackKeywords,
                )
            )

        context.addCallbacks = addCallbacks

        def f(x, y, z):
            return None

        context.addCallback(f, 2, z=3)
        self.assertEqual(called, [(f, _passthrough, (2,), {"z": 3}, None, None)])

    @withActionContext
    def test_addCallbackReturnsSelf(self):
        """
        L{DeferredContext.addCallback} returns the L{DeferredContext}.
        """
        result = Deferred()
        context = DeferredContext(result)
        self.assertIs(context, context.addCallback(lambda x: None))

    @withActionContext
    def test_addErrbackCallsAddCallbacks(self):
        """
        L{DeferredContext.addErrback} passes its arguments on to
        L{DeferredContext.addCallbacks}.
        """
        result = Deferred()
        context = DeferredContext(result)
        called = []

        def addCallbacks(
            callback,
            errback,
            callbackArgs=None,
            callbackKeywords=None,
            errbackArgs=None,
            errbackKeywords=None,
        ):
            called.append(
                (
                    callback,
                    errback,
                    callbackArgs,
                    callbackKeywords,
                    errbackArgs,
                    errbackKeywords,
                )
            )

        context.addCallbacks = addCallbacks

        def f(x, y, z):
            pass

        context.addErrback(f, 2, z=3)
        self.assertEqual(called, [(_passthrough, f, None, None, (2,), {"z": 3})])

    @withActionContext
    def test_addErrbackReturnsSelf(self):
        """
        L{DeferredContext.addErrback} returns the L{DeferredContext}.
        """
        result = Deferred()
        context = DeferredContext(result)
        self.assertIs(context, context.addErrback(lambda x: None))

    @withActionContext
    def test_addBothCallsAddCallbacks(self):
        """
        L{DeferredContext.addBoth} passes its arguments on to
        L{DeferredContext.addCallbacks}.
        """
        result = Deferred()
        context = DeferredContext(result)
        called = []

        def addCallbacks(
            callback,
            errback,
            callbackArgs=None,
            callbackKeywords=None,
            errbackArgs=None,
            errbackKeywords=None,
        ):
            called.append(
                (
                    callback,
                    errback,
                    callbackArgs,
                    callbackKeywords,
                    errbackArgs,
                    errbackKeywords,
                )
            )

        context.addCallbacks = addCallbacks

        def f(x, y, z):
            return None

        context.addBoth(f, 2, z=3)
        self.assertEqual(called, [(f, f, (2,), {"z": 3}, (2,), {"z": 3})])

    @withActionContext
    def test_addBothReturnsSelf(self):
        """
        L{DeferredContext.addBoth} returns the L{DeferredContext}.
        """
        result = Deferred()
        context = DeferredContext(result)
        self.assertIs(context, context.addBoth(lambda x: None))


class RedirectLogsForTrialTests(TestCase):
    """
    Tests for L{redirectLogsForTrial}.
    """

    def assertDestinationAdded(self, programPath):
        """
        Assert that when running under the given program a new destination is
        added by L{redirectLogsForTrial}.

        @param programPath: A path to a program.
        @type programPath: L{str}
        """
        destination = _RedirectLogsForTrial(FakeSys([programPath], ""))()
        self.assertIsInstance(destination, TwistedDestination)
        # If this was not added as destination, removing it will raise an
        # exception:
        try:
            removeDestination(destination)
        except ValueError:
            self.fail("Destination was not added.")

    def test_withTrial(self):
        """
        When C{sys.argv[0]} is C{"trial"} a new destination is added by
        L{redirectLogsForTrial}.
        """
        self.assertDestinationAdded("trial")

    def test_withAbsoluteTrialPath(self):
        """
        When C{sys.argv[0]} is an absolute path ending with C{"trial"} a new
        destination is added by L{redirectLogsForTrial}.
        """
        self.assertDestinationAdded("/usr/bin/trial")

    def test_withRelativeTrialPath(self):
        """
        When C{sys.argv[0]} is a relative path ending with C{"trial"} a new
        destination is added by L{redirectLogsForTrial}.
        """
        self.assertDestinationAdded("./trial")

    def test_withoutTrialNoDestination(self):
        """
        When C{sys.argv[0]} is not C{"trial"} no destination is added by
        L{redirectLogsForTrial}.
        """
        originalDestinations = Logger._destinations._destinations[:]
        _RedirectLogsForTrial(FakeSys(["myprogram.py"], ""))()
        self.assertEqual(Logger._destinations._destinations, originalDestinations)

    def test_trialAsPathNoDestination(self):
        """
        When C{sys.argv[0]} has C{"trial"} as directory name but not program
        name no destination is added by L{redirectLogsForTrial}.
        """
        originalDestinations = Logger._destinations._destinations[:]
        _RedirectLogsForTrial(FakeSys(["./trial/myprogram.py"], ""))()
        self.assertEqual(Logger._destinations._destinations, originalDestinations)

    def test_withoutTrialResult(self):
        """
        When not running under I{trial} L{None} is returned.
        """
        self.assertIs(None, _RedirectLogsForTrial(FakeSys(["myprogram.py"], ""))())

    def test_noDuplicateAdds(self):
        """
        If a destination has already been added, calling
        L{redirectLogsForTrial} a second time does not add another destination.
        """
        redirect = _RedirectLogsForTrial(FakeSys(["trial"], ""))
        destination = redirect()
        self.addCleanup(removeDestination, destination)
        originalDestinations = Logger._destinations._destinations[:]
        redirect()
        self.assertEqual(Logger._destinations._destinations, originalDestinations)

    def test_noDuplicateAddsResult(self):
        """
        If a destination has already been added, calling
        L{redirectLogsForTrial} a second time returns L{None}.
        """
        redirect = _RedirectLogsForTrial(FakeSys(["trial"], ""))
        destination = redirect()
        self.addCleanup(removeDestination, destination)
        result = redirect()
        self.assertIs(result, None)

    def test_publicAPI(self):
        """
        L{redirectLogsForTrial} is an instance of L{_RedirectLogsForTrial}.
        """
        self.assertIsInstance(redirectLogsForTrial, _RedirectLogsForTrial)

    def test_defaults(self):
        """
        By default L{redirectLogsForTrial} looks at L{sys.argv}.
        """
        self.assertEqual(redirectLogsForTrial._sys, sys)


class TwistedDestinationTests(TestCase):
    """
    Tests for L{TwistedDestination}.
    """

    def redirect_to_twisted(self):
        """
        Redirect Eliot logs to Twisted.

        @return: L{list} of L{dict} - the log messages written to Twisted will
             eventually be appended to this list.
        """
        written = []

        def got_event(event):
            if event.get("log_namespace") == "eliot":
                written.append((event["log_level"].name, event["eliot"]))

        globalLogPublisher.addObserver(got_event)
        self.addCleanup(globalLogPublisher.removeObserver, got_event)
        destination = TwistedDestination()
        addDestination(destination)
        self.addCleanup(removeDestination, destination)
        return written

    def redirect_to_list(self):
        """
        Redirect Eliot logs to a list.

        @return: L{list} that will have eventually have the written Eliot
            messages added to it.
        """
        written = []
        destination = written.append
        addDestination(destination)
        self.addCleanup(removeDestination, destination)
        return written

    def test_normalMessages(self):
        """
        Regular eliot messages are pretty-printed to the given L{LogPublisher}.
        """
        writtenToTwisted = self.redirect_to_twisted()
        written = self.redirect_to_list()
        logger = Logger()
        Message.new(x=123, y=456).write(logger)
        self.assertEqual(writtenToTwisted, [("info", written[0])])

    def test_tracebackMessages(self):
        """
        Traceback eliot messages are written to the given L{LogPublisher} with
        the traceback formatted for easier reading.
        """
        writtenToTwisted = self.redirect_to_twisted()
        written = self.redirect_to_list()
        logger = Logger()

        def raiser():
            raise RuntimeError("because")

        try:
            raiser()
        except Exception:
            write_traceback(logger)
        self.assertEqual(writtenToTwisted, [("critical", written[0])])


class InlineCallbacksTests(TestCase):
    """Tests for C{inline_callbacks}."""

    # Get our custom assertion failure messages *and* the standard ones.
    longMessage = True

    def _a_b_test(self, logger, g):
        """A yield was done in between messages a and b inside C{inline_callbacks}."""
        with start_action(action_type="the-action"):
            self.assertIs(None, self.successResultOf(g()))
        assert_expected_action_tree(self, logger, "the-action", ["a", "yielded", "b"])

    @capture_logging(None)
    def test_yield_none(self, logger):
        def g():
            Message.log(message_type="a")
            yield
            Message.log(message_type="b")

        g = inline_callbacks(g, debug=True)

        self._a_b_test(logger, g)

    @capture_logging(None)
    def test_yield_fired_deferred(self, logger):
        def g():
            Message.log(message_type="a")
            yield succeed(None)
            Message.log(message_type="b")

        g = inline_callbacks(g, debug=True)

        self._a_b_test(logger, g)

    @capture_logging(None)
    def test_yield_unfired_deferred(self, logger):
        waiting = Deferred()

        def g():
            Message.log(message_type="a")
            yield waiting
            Message.log(message_type="b")

        g = inline_callbacks(g, debug=True)

        with start_action(action_type="the-action"):
            d = g()
            self.assertNoResult(waiting)
            waiting.callback(None)
            self.assertIs(None, self.successResultOf(d))
        assert_expected_action_tree(self, logger, "the-action", ["a", "yielded", "b"])

    @capture_logging(None)
    def test_returnValue(self, logger):
        result = object()

        @inline_callbacks
        def g():
            if False:
                yield
            returnValue(result)

        with start_action(action_type="the-action"):
            d = g()
            self.assertIs(result, self.successResultOf(d))

        assert_expected_action_tree(self, logger, "the-action", [])

    @capture_logging(None)
    def test_returnValue_in_action(self, logger):
        result = object()

        @inline_callbacks
        def g():
            if False:
                yield
            with start_action(action_type="g"):
                returnValue(result)

        with start_action(action_type="the-action"):
            d = g()
            self.assertIs(result, self.successResultOf(d))

        assert_expected_action_tree(self, logger, "the-action", [{"g": []}])

    @capture_logging(None)
    def test_nested_returnValue(self, logger):
        result = object()
        another = object()

        def g():
            d = h()
            # Run h through to the end but ignore its result.
            yield d
            # Give back _our_ result.
            returnValue(result)

        g = inline_callbacks(g, debug=True)

        def h():
            yield
            returnValue(another)

        h = inline_callbacks(h, debug=True)

        with start_action(action_type="the-action"):
            d = g()
            self.assertIs(result, self.successResultOf(d))

        assert_expected_action_tree(self, logger, "the-action", ["yielded", "yielded"])

    @capture_logging(None)
    def test_async_returnValue(self, logger):
        result = object()
        waiting = Deferred()

        @inline_callbacks
        def g():
            yield waiting
            returnValue(result)

        with start_action(action_type="the-action"):
            d = g()
            waiting.callback(None)
            self.assertIs(result, self.successResultOf(d))

    @capture_logging(None)
    def test_nested_async_returnValue(self, logger):
        result = object()
        another = object()

        waiting = Deferred()

        @inline_callbacks
        def g():
            yield h()
            returnValue(result)

        @inline_callbacks
        def h():
            yield waiting
            returnValue(another)

        with start_action(action_type="the-action"):
            d = g()
            waiting.callback(None)
            self.assertIs(result, self.successResultOf(d))