<commit_before>"""
Tests for L{eliot.twisted}.
"""

from __future__ import absolute_import, unicode_literals, print_function

import sys
from functools import wraps

try:
    from twisted.internet.defer import Deferred, succeed, fail
    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
    )

from .._action import start_action, current_action, Action, TaskLevel
from .._output import MemoryLogger, Logger
from .._message import Message
from ..testing import assertContainsFields
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_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(<commit_msg>Add a failing test for the addCallbacks behavior<commit_after>"""
Tests for L{eliot.twisted}.
"""

from __future__ import absolute_import, unicode_literals, print_function

import sys
from functools import wraps

try:
    from twisted.internet.defer import Deferred, succeed, fail
    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
    )

from .._action import start_action, current_action, Action, TaskLevel
from .._output import MemoryLogger, Logger
from .._message import Message
from ..testing import assertContainsFields
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_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(
{'fraction_non_alphanumeric': 0.09669603524229074, 'fraction_numerical': 0.003303964757709251, 'mean_word_length': 2.538971161340608, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6510264', 'n_tokens_mistral': 2575, 'n_tokens_neox': 2508, 'n_words': 694}