# Path: ntfy/cli.py
# def main(cli_args=None):
#     if cli_args is not None:
#         args = parser.parse_args(cli_args)
#     else:
#         args = parser.parse_args()
# 
#     logging.config.dictConfig({
#         'version': 1,
#         'disable_existing_loggers': False,
#         'formatters': {
#             'default': {
#                 'format': '%(levelname)s: %(message)s'
#             },
#         },
#         'handlers': {
#             'default': {
#                 'level': args.log_level,
#                 'class': 'logging.StreamHandler',
#                 'formatter': 'default',
#             },
#         },
#         'loggers': {
#             '': {
#                 'handlers': ['default'],
#                 'level': args.log_level,
#                 'propagate': True,
#             }
#         }
#     })
# 
#     if args.config is not None:
#         config = load_config(args.config)
#     elif path.exists(path.expanduser(DEFAULT_CONFIG)):
#         config = load_config(DEFAULT_CONFIG)
#     elif path.exists(OLD_DEFAULT_CONFIG):
#         config = load_config(OLD_DEFAULT_CONFIG)
#     elif path.exists(path.expanduser(SITE_DEFAULT_CONFIG)):
#         config = load_config(SITE_DEFAULT_CONFIG)
#     else:  # get default config and print message about missing file
#         config = load_config()
# 
#     if 'NTFY_BACKENDS' in environ:
#         config['backends'] = environ['NTFY_BACKENDS'].split(',')
# 
#     if args.backend:
#         config['backends'] = args.backend
# 
#     if args.option is None:
#         args.option = {}
#     for backend, backend_options in args.option.items():
#         if backend is not None:
#             config.setdefault(backend, {}).update(backend_options)
# 
#     if getattr(args, 'func', None) == run_cmd and args.longer_than is None and\
#             'longer_than' in config:
#         args.longer_than = config['longer_than']
# 
#     if getattr(args, 'func', None) == run_cmd and 'hide_command' in config:
#         args.hide_command = config['hide_command']
# 
#     if hasattr(args, 'func'):
#         message, retcode = args.func(args)
#         if message is None:
#             return 0
#         if emojize is not None and not args.no_emoji:
#             message = emojize(message, use_aliases=True)
#         return notify(
#             message,
#             args.title,
#             config,
#             retcode=retcode,
#             **dict(args.option.get(None, [])))
#     else:
#         parser.print_help()
# 
# Path: ntfy/cli.py
# def auto_done(args):
#     if args.longer_than:
#         print('export AUTO_NTFY_DONE_LONGER_THAN=-L{}'.format(
#             args.longer_than))
#     if args.unfocused_only:
#         print('export AUTO_NTFY_DONE_UNFOCUSED_ONLY=-b')
#     if args.shell == 'bash':
#         print('source {}'.format(sh_quote(scripts['bash-preexec.sh'])))
#     print('source {}'.format(sh_quote(scripts['auto-ntfy-done.sh'])))
#     print("# To use ntfy's shell integration, run "
#           "this and add it to your shell's rc file:")
#     print('# eval "$(ntfy shell-integration)"')
#     return None, None
# 
# def run_cmd(args):
#     if getattr(args, 'pid', False):
#         return watch_pid(args)
#     if not args.command:
#         if args.formatter:
#             args.command, retcode, duration = args.formatter
#             args.command, retcode, duration = ([args.command], int(retcode),
#                                                int(duration))
#             args.option.setdefault('linux', {}).setdefault('transient', 'true')
#             stdout, stderr = None, None
#         else:
#             sys.stderr.write('usage: ntfy done [-h|-L N] command\n'
#                              'ntfy done: error: the following arguments '
#                              'are required: command\n')
#             sys.exit(1)
#     else:
#         if args.stdout and args.stderr:
#             out = PIPE
#             err = STDOUT
#         else:
#             out = PIPE if args.stdout else None
#             err = PIPE if args.stderr else None
#         start_time = time()
#         process = Popen(args.command, stdout=out, stderr=err)
#         stdout, stderr = process.communicate()
#         process.wait()
#         duration = time() - start_time
#         retcode = process.returncode
#     if args.longer_than is not None and duration <= args.longer_than:
#         return None, None
#     if args.unfocused_only and is_focused():
#         return None, None
#     message = _result_message(args.command if not args.hide_command else None,
#                               retcode, stdout, stderr, duration,
#                               emojize is not None and not args.no_emoji)
#     return message, retcode


from time import time
from unittest import TestCase, main
from mock import MagicMock, Mock, patch
from ntfy.cli import main as ntfy_main
from ntfy.cli import auto_done, run_cmd

    def test_formatter_failure(self):
        args = MagicMock()
        args.pid = None
        args.command = None
        args.formatter = ("false", 1, 10)
        args.longer_than = -1
        args.unfocused_only = False
        args.hide_command = False
        self.assertEqual(('"false" failed (code 1) in 0:10 minutes', 1),
                         run_cmd(args))


class TestMain(TestCase):
    @patch('ntfy.backends.default.notify')
    def test_args(self, mock_notify):
        mock_notify.return_value = None
        self.assertEquals(0,
                          ntfy_main([
                              '-o', 'foo', 'bar', '-b', 'default', '-t',
                              'TITLE', 'send', 'test'
                          ]))
        mock_notify.assert_called_once_with(
            message='test', title='TITLE', foo='bar', retcode=0)


class ShellIntegrationTestCase(TestCase):
    def test_shellintegration_printout(self):
        # not mocking print to check calls because test runner uses print...
        args = MagicMock()

# Path: ntfy/cli.py
# def main(cli_args=None):
#     if cli_args is not None:
#         args = parser.parse_args(cli_args)
#     else:
#         args = parser.parse_args()
# 
#     logging.config.dictConfig({
#         'version': 1,
#         'disable_existing_loggers': False,
#         'formatters': {
#             'default': {
#                 'format': '%(levelname)s: %(message)s'
#             },
#         },
#         'handlers': {
#             'default': {
#                 'level': args.log_level,
#                 'class': 'logging.StreamHandler',
#                 'formatter': 'default',
#             },
#         },
#         'loggers': {
#             '': {
#                 'handlers': ['default'],
#                 'level': args.log_level,
#                 'propagate': True,
#             }
#         }
#     })
# 
#     if args.config is not None:
#         config = load_config(args.config)
#     elif path.exists(path.expanduser(DEFAULT_CONFIG)):
#         config = load_config(DEFAULT_CONFIG)
#     elif path.exists(OLD_DEFAULT_CONFIG):
#         config = load_config(OLD_DEFAULT_CONFIG)
#     elif path.exists(path.expanduser(SITE_DEFAULT_CONFIG)):
#         config = load_config(SITE_DEFAULT_CONFIG)
#     else:  # get default config and print message about missing file
#         config = load_config()
# 
#     if 'NTFY_BACKENDS' in environ:
#         config['backends'] = environ['NTFY_BACKENDS'].split(',')
# 
#     if args.backend:
#         config['backends'] = args.backend
# 
#     if args.option is None:
#         args.option = {}
#     for backend, backend_options in args.option.items():
#         if backend is not None:
#             config.setdefault(backend, {}).update(backend_options)
# 
#     if getattr(args, 'func', None) == run_cmd and args.longer_than is None and\
#             'longer_than' in config:
#         args.longer_than = config['longer_than']
# 
#     if getattr(args, 'func', None) == run_cmd and 'hide_command' in config:
#         args.hide_command = config['hide_command']
# 
#     if hasattr(args, 'func'):
#         message, retcode = args.func(args)
#         if message is None:
#             return 0
#         if emojize is not None and not args.no_emoji:
#             message = emojize(message, use_aliases=True)
#         return notify(
#             message,
#             args.title,
#             config,
#             retcode=retcode,
#             **dict(args.option.get(None, [])))
#     else:
#         parser.print_help()
# 
# Path: ntfy/cli.py
# def auto_done(args):
#     if args.longer_than:
#         print('export AUTO_NTFY_DONE_LONGER_THAN=-L{}'.format(
#             args.longer_than))
#     if args.unfocused_only:
#         print('export AUTO_NTFY_DONE_UNFOCUSED_ONLY=-b')
#     if args.shell == 'bash':
#         print('source {}'.format(sh_quote(scripts['bash-preexec.sh'])))
#     print('source {}'.format(sh_quote(scripts['auto-ntfy-done.sh'])))
#     print("# To use ntfy's shell integration, run "
#           "this and add it to your shell's rc file:")
#     print('# eval "$(ntfy shell-integration)"')
#     return None, None
# 
# def run_cmd(args):
#     if getattr(args, 'pid', False):
#         return watch_pid(args)
#     if not args.command:
#         if args.formatter:
#             args.command, retcode, duration = args.formatter
#             args.command, retcode, duration = ([args.command], int(retcode),
#                                                int(duration))
#             args.option.setdefault('linux', {}).setdefault('transient', 'true')
#             stdout, stderr = None, None
#         else:
#             sys.stderr.write('usage: ntfy done [-h|-L N] command\n'
#                              'ntfy done: error: the following arguments '
#                              'are required: command\n')
#             sys.exit(1)
#     else:
#         if args.stdout and args.stderr:
#             out = PIPE
#             err = STDOUT
#         else:
#             out = PIPE if args.stdout else None
#             err = PIPE if args.stderr else None
#         start_time = time()
#         process = Popen(args.command, stdout=out, stderr=err)
#         stdout, stderr = process.communicate()
#         process.wait()
#         duration = time() - start_time
#         retcode = process.returncode
#     if args.longer_than is not None and duration <= args.longer_than:
#         return None, None
#     if args.unfocused_only and is_focused():
#         return None, None
#     message = _result_message(args.command if not args.hide_command else None,
#                               retcode, stdout, stderr, duration,
#                               emojize is not None and not args.no_emoji)
#     return message, retcode


# Path: tests/test_cli.py
from time import time
from unittest import TestCase, main
from mock import MagicMock, Mock, patch
from ntfy.cli import main as ntfy_main
from ntfy.cli import auto_done, run_cmd


    def test_formatter_failure(self):
        args = MagicMock()
        args.pid = None
        args.command = None
        args.formatter = ("false", 1, 10)
        args.longer_than = -1
        args.unfocused_only = False
        args.hide_command = False
        self.assertEqual(('"false" failed (code 1) in 0:10 minutes', 1),
                         run_cmd(args))


class TestMain(TestCase):
    @patch('ntfy.backends.default.notify')
    def test_args(self, mock_notify):
        mock_notify.return_value = None
        self.assertEquals(0,
                          ntfy_main([
                              '-o', 'foo', 'bar', '-b', 'default', '-t',
                              'TITLE', 'send', 'test'
                          ]))
        mock_notify.assert_called_once_with(
            message='test', title='TITLE', foo='bar', retcode=0)


class ShellIntegrationTestCase(TestCase):
    def test_shellintegration_printout(self):
        # not mocking print to check calls because test runner uses print...
        args = MagicMock()

        auto_done(args)