<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from unittest import TestCase
import irc3
import irc3d
from irc3.compat import PY3
from irc3.compat import asyncio
import tempfile
import time
import os

try:
    from unittest import mock
except ImportError:  # pragma: no cover
    import mock

MagicMock = mock.MagicMock
patch = mock.patch
call = mock.call

passwd_ini = """
[irc.freenode.net]
irc3=password

[twitter]
key=key
secret=secret
token=token
token_secret=token_secret
"""


def ini2config(data, type='bot'):
    if PY3:
        data = data.encode('utf8')
    with tempfile.NamedTemporaryFile(prefix='irc3-') as fd:
        fd.write(data)
        fd.flush()
        data = irc3.utils.parse_config(type, fd.name)
    return data


def call_later(i, func, *args):
    if func.__name__ in dir(IrcBot):
        func(*args)
    return asyncio.Handle(func, args, asyncio.get_event_loop())


def call_soon(func, *args):
    func(*args)
    return asyncio.Handle(func, args,  asyncio.get_event_loop())


class IrcBot(irc3.IrcBot):

    def __init__(self, **config):
        self.check_required()
        if 'loop' not in config:
            loop = asyncio.new_event_loop()
            loop = mock.create_autospec(loop, spec_set=True)
            loop.call_later = call_later
            loop.call_soon = call_soon
            loop.time.return_value = 10
            config.update(testing=True, async=False, level=1000,
                          loop=loop)
        else:
            config.update(testing=True, level=1000)
        super(IrcBot, self).__init__(**config)
        self.protocol = irc3.IrcConnection()
        self.protocol.closed = False
        self.protocol.factory = self
        self.protocol.transport = MagicMock()
        self.protocol.write = MagicMock()

    def check_required(self):  # pragma: no cover
        dirname = os.path.expanduser('~/.irc3')
        if not os.path.isdir(dirname):
            os.makedirs(dirname)
        filename = os.path.expanduser('~/.irc3/passwd.ini')
        if not os.path.isfile(filename):
            with open(filename, 'w') as fd:
                fd.write(passwd_ini)

    def test(self, data, show=True):
        self.dispatch(data)
        if show:
            for line in self.sent:  # pragma: no cover
                if PY3:
                    print(line)
                else:
                    print(line.encode('utf8'))

    @property
    def sent(self):
        values = [tuple(c)[0][0] for c in self.protocol.write.call_args_list]
        self.protocol.write.reset_mock()
        if not PY3:  # pragma: no cover
            return [v.encode('utf8') for v in values]
        return values


class IrcTestCase(TestCase):

    def patch_requests(self, **kwargs):
        self.patcher = patch('requests.Session.request')
        self.addCleanup(self.patcher.stop)
        request = self.patcher.start()

        filename = kwargs.pop('filename', None)
        if filename:<commit_msg>fix tests error when they called from another dir<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from unittest import TestCase
import irc3
import irc3d
from irc3.compat import PY3
from irc3.compat import asyncio
import tempfile
import time
import os

try:
    from unittest import mock
except ImportError:  # pragma: no cover
    import mock

MagicMock = mock.MagicMock
patch = mock.patch
call = mock.call
PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

passwd_ini = """
[irc.freenode.net]
irc3=password

[twitter]
key=key
secret=secret
token=token
token_secret=token_secret
"""


def ini2config(data, type='bot'):
    if PY3:
        data = data.encode('utf8')
    with tempfile.NamedTemporaryFile(prefix='irc3-') as fd:
        fd.write(data)
        fd.flush()
        data = irc3.utils.parse_config(type, fd.name)
    return data


def call_later(i, func, *args):
    if func.__name__ in dir(IrcBot):
        func(*args)
    return asyncio.Handle(func, args, asyncio.get_event_loop())


def call_soon(func, *args):
    func(*args)
    return asyncio.Handle(func, args,  asyncio.get_event_loop())


class IrcBot(irc3.IrcBot):

    def __init__(self, **config):
        self.check_required()
        if 'loop' not in config:
            loop = asyncio.new_event_loop()
            loop = mock.create_autospec(loop, spec_set=True)
            loop.call_later = call_later
            loop.call_soon = call_soon
            loop.time.return_value = 10
            config.update(testing=True, async=False, level=1000,
                          loop=loop)
        else:
            config.update(testing=True, level=1000)
        super(IrcBot, self).__init__(**config)
        self.protocol = irc3.IrcConnection()
        self.protocol.closed = False
        self.protocol.factory = self
        self.protocol.transport = MagicMock()
        self.protocol.write = MagicMock()

    def check_required(self):  # pragma: no cover
        dirname = os.path.expanduser('~/.irc3')
        if not os.path.isdir(dirname):
            os.makedirs(dirname)
        filename = os.path.expanduser('~/.irc3/passwd.ini')
        if not os.path.isfile(filename):
            with open(filename, 'w') as fd:
                fd.write(passwd_ini)

    def test(self, data, show=True):
        self.dispatch(data)
        if show:
            for line in self.sent:  # pragma: no cover
                if PY3:
                    print(line)
                else:
                    print(line.encode('utf8'))

    @property
    def sent(self):
        values = [tuple(c)[0][0] for c in self.protocol.write.call_args_list]
        self.protocol.write.reset_mock()
        if not PY3:  # pragma: no cover
            return [v.encode('utf8') for v in values]
        return values


class IrcTestCase(TestCase):

    project_path = PROJECT_PATH

    def patch_requests(self, **kwargs):
        self.patcher = patch('requests.Session.request')
        self.addCleanup(self.patcher.stop)
        request = self.patcher.start()

        filename = kwargs.pop('filename', None)
        if filename:
            filename = os.path.join(self.project_path, filename)
{'fraction_non_alphanumeric': 0.11109314359637774, 'fraction_numerical': 0.01034928848641656, 'mean_word_length': 2.396485447556288, 'pattern_counts': {'":': 0, '<': 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': '5474238', 'n_tokens_mistral': 2002, 'n_tokens_neox': 1914, 'n_words': 444}