# Path: auxlib/logz.py
# def attach_stderr(level=INFO):
#     has_stderr_handler = any(handler.name == 'stderr' for handler in root_log.handlers)
#     if not has_stderr_handler:
#         handler = StreamHandler(stderr)
#         handler.name = 'stderr'
#         if level is not None:
#             handler.setLevel(level)
#         handler.setFormatter(DEBUG_FORMATTER if level == DEBUG else INFO_FORMATTER)
#         root_log.addHandler(handler)
#         return True
#     else:
#         return False
# 
# def detach_stderr():
#     for handler in root_log.handlers:
#         if handler.name == 'stderr':
#             root_log.removeHandler(handler)
#             return True
#     return False
# 
# def initialize_logging(level=INFO):
#     attach_stderr(level)
# 
# def stringify(obj, content_max_len=0):
#     def bottle_builder(builder, bottle_object):
#         builder.append("{0} {1}{2} {3}".format(bottle_object.method,
#                                                bottle_object.path,
#                                                bottle_object.environ.get('QUERY_STRING', ''),
#                                                bottle_object.get('SERVER_PROTOCOL')))
#         builder += ["{0}: {1}".format(key, value) for key, value in bottle_object.headers.items()]
#         builder.append('')
#         body = bottle_object.body.read().strip()
#         if body:
#             builder.append(body)
# 
#     def requests_models_PreparedRequest_builder(builder, request_object):
#         builder.append(">>{0} {1} {2}".format(request_object.method, request_object.path_url,
#                                               request_object.url.split(':', 1)[0].upper()))
#         builder.extend("> {0}: {1}".format(key, value)
#                        for key, value in sorted(request_object.headers.items(),
#                                                 key=request_header_sort_key))
#         builder.append('')
#         if request_object.body:
#             builder.append(request_object.body)
# 
#     def requests_models_Response_builder(builder, response_object):
#         builder.append("<<{0} {1} {2}".format(response_object.url.split(':', 1)[0].upper(),
#                                               response_object.status_code, response_object.reason))
#         builder.extend("< {0}: {1}".format(key, value)
#                        for key, value in sorted(response_object.headers.items(),
#                                                 key=response_header_sort_key))
#         elapsed = text_type(response_object.elapsed).split(':', 1)[-1]
#         builder.append('< Elapsed: {0}'.format(elapsed))
#         if content_max_len:
#             builder.append('')
#             content_type = response_object.headers.get('Content-Type')
#             if content_type == 'application/json':
#                 content = pformat(response_object.json(), indent=2)
#                 content = content[:content_max_len] if len(content) > content_max_len else content
#                 builder.append(content)
#                 builder.append('')
#             elif content_type is not None and (content_type.startswith('text/')
#                                                or content_type == 'application/xml'):
#                 text = response_object.text
#                 content = text[:content_max_len] if len(text) > content_max_len else text
#                 builder.append(content)
# 
#     try:
#         name = fullname(obj)
#         builder = ['']  # start with new line
#         if name.startswith('bottle.'):
#             bottle_builder(builder, obj)
#         elif name.endswith('requests.models.PreparedRequest'):
#             requests_models_PreparedRequest_builder(builder, obj)
#         elif name.endswith('requests.models.Response'):
#             if getattr(obj, 'request'):
#                 requests_models_PreparedRequest_builder(builder, obj.request)
#             else:
#                 log.info("request is 'None' for Response object with url %s", obj.url)
#             requests_models_Response_builder(builder, obj)
#         else:
#             return None
#         builder.append('')  # end with new line
#         return "\n".join(builder)
#     except Exception as e:
#         log.exception(e)


from logging import getLogger
from unittest import TestCase
from requests import Request
from auxlib.logz import attach_stderr, detach_stderr, initialize_logging, stringify
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function



log = getLogger(__name__)


class TestLoggingSetup(TestCase):

    def test_basic_stderr(self):
        detach_stderr()
        assert attach_stderr()
        assert not attach_stderr()
        assert detach_stderr()
        assert not detach_stderr()

# Path: auxlib/logz.py
# def attach_stderr(level=INFO):
#     has_stderr_handler = any(handler.name == 'stderr' for handler in root_log.handlers)
#     if not has_stderr_handler:
#         handler = StreamHandler(stderr)
#         handler.name = 'stderr'
#         if level is not None:
#             handler.setLevel(level)
#         handler.setFormatter(DEBUG_FORMATTER if level == DEBUG else INFO_FORMATTER)
#         root_log.addHandler(handler)
#         return True
#     else:
#         return False
# 
# def detach_stderr():
#     for handler in root_log.handlers:
#         if handler.name == 'stderr':
#             root_log.removeHandler(handler)
#             return True
#     return False
# 
# def initialize_logging(level=INFO):
#     attach_stderr(level)
# 
# def stringify(obj, content_max_len=0):
#     def bottle_builder(builder, bottle_object):
#         builder.append("{0} {1}{2} {3}".format(bottle_object.method,
#                                                bottle_object.path,
#                                                bottle_object.environ.get('QUERY_STRING', ''),
#                                                bottle_object.get('SERVER_PROTOCOL')))
#         builder += ["{0}: {1}".format(key, value) for key, value in bottle_object.headers.items()]
#         builder.append('')
#         body = bottle_object.body.read().strip()
#         if body:
#             builder.append(body)
# 
#     def requests_models_PreparedRequest_builder(builder, request_object):
#         builder.append(">>{0} {1} {2}".format(request_object.method, request_object.path_url,
#                                               request_object.url.split(':', 1)[0].upper()))
#         builder.extend("> {0}: {1}".format(key, value)
#                        for key, value in sorted(request_object.headers.items(),
#                                                 key=request_header_sort_key))
#         builder.append('')
#         if request_object.body:
#             builder.append(request_object.body)
# 
#     def requests_models_Response_builder(builder, response_object):
#         builder.append("<<{0} {1} {2}".format(response_object.url.split(':', 1)[0].upper(),
#                                               response_object.status_code, response_object.reason))
#         builder.extend("< {0}: {1}".format(key, value)
#                        for key, value in sorted(response_object.headers.items(),
#                                                 key=response_header_sort_key))
#         elapsed = text_type(response_object.elapsed).split(':', 1)[-1]
#         builder.append('< Elapsed: {0}'.format(elapsed))
#         if content_max_len:
#             builder.append('')
#             content_type = response_object.headers.get('Content-Type')
#             if content_type == 'application/json':
#                 content = pformat(response_object.json(), indent=2)
#                 content = content[:content_max_len] if len(content) > content_max_len else content
#                 builder.append(content)
#                 builder.append('')
#             elif content_type is not None and (content_type.startswith('text/')
#                                                or content_type == 'application/xml'):
#                 text = response_object.text
#                 content = text[:content_max_len] if len(text) > content_max_len else text
#                 builder.append(content)
# 
#     try:
#         name = fullname(obj)
#         builder = ['']  # start with new line
#         if name.startswith('bottle.'):
#             bottle_builder(builder, obj)
#         elif name.endswith('requests.models.PreparedRequest'):
#             requests_models_PreparedRequest_builder(builder, obj)
#         elif name.endswith('requests.models.Response'):
#             if getattr(obj, 'request'):
#                 requests_models_PreparedRequest_builder(builder, obj.request)
#             else:
#                 log.info("request is 'None' for Response object with url %s", obj.url)
#             requests_models_Response_builder(builder, obj)
#         else:
#             return None
#         builder.append('')  # end with new line
#         return "\n".join(builder)
#     except Exception as e:
#         log.exception(e)


# Path: tests/test_logz.py
from logging import getLogger
from unittest import TestCase
from requests import Request
from auxlib.logz import attach_stderr, detach_stderr, initialize_logging, stringify

# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function



log = getLogger(__name__)


class TestLoggingSetup(TestCase):

    def test_basic_stderr(self):
        detach_stderr()
        assert attach_stderr()
        assert not attach_stderr()
        assert detach_stderr()
        assert not detach_stderr()

        assert attach_stderr()