# Path: tests/commands/execution/utils.py
# def get_execution_data_mock():
#     exec_id = EXECUTION_DATA['id']
#     datum_id = OUTPUT_DATUM_DATA['id']
#     m = requests_mock.mock()
#     project_id = PROJECT_DATA['id']
#     execution_counter = EXECUTION_DATA['counter']
#     m.get(f'{API_PREFIX}projects/{project_id}/', json=PROJECT_DATA)
#     m.get(f'{API_PREFIX}executions/', json={'results': [EXECUTION_DATA]})
#     m.get(f'{API_PREFIX}executions/{exec_id}/', json=EXECUTION_DATA)
#     m.get(f'{API_PREFIX}executions/{exec_id}/events/', json=EVENT_RESPONSE_DATA)
#     m.get(f'{API_PREFIX}data/?output_execution={exec_id}&limit=9000', json=OUTPUT_DATUM_RESPONSE_DATA)
#     m.get(f'{API_PREFIX}data/{datum_id}/download/', json=OUTPUT_DATUM_DOWNLOAD_RESPONSE_DATA)
#     execution_by_counter_url = f'{API_PREFIX}executions/{project_id}:{execution_counter}/'
#     m.get(url=get_startswith_re(execution_by_counter_url), json=EXECUTION_DATA)
#     m.delete(execution_by_counter_url, json={'ok': True})
#     m.post(re.compile('^https://app.valohai.com/api/v0/data/(.+?)/purge/$'), json={'ok': True})
#     return m
# 
# Path: tests/fixture_data.py
# EXECUTION_DATA = {
#     'counter': random.randint(1, 100),
#     'ctime': '2017-02-08T11:09:16.120102Z',
#     'id': execution_id,
#     'project': PROJECT_DATA,
#     'commit': {
#         'repository': 666,
#         'identifier': '000',
#         'ref': 'master',
#         'commit_time': '2017-02-15T08:46:58Z',
#         'url': 'https://app.valohai.com/api/v0/commits/7/'
#     },
#     'task': None,
#     'duration': 777,
#     'status': 'complete',
#     'step': 'run training',
#     'url': f'https://app.valohai.com/api/v0/executions/{execution_id}/',
#     'urls': {
#         'copy': 'https://app.valohai.com/api/v0/executions/34/copy/',
#         'display': 'https://app.valohai.com/p/test/mnist/execution/34/',
#         'stop': 'https://app.valohai.com/api/v0/executions/34/stop/',
#     },
#     'parameters': {
#         'dropout': 0.9,
#         'learning_rate': 0.001,
#         'max_steps': 300,
#     },
#     'outputs': [
#         OUTPUT_DATUM_DATA,
#     ],
#     'environment': {
#         'id': '88888888-8888-8888-8888-888888888888',
#         'name': 'local',
#         'owner': None,
#         'unfinished_job_count': 0,
#     },
#     'cumulative_metadata': {
#         'oispa': 'beer',
#     },
# }
# 
# Path: valohai_cli/commands/execution/logs.py
# @click.command()
# @counter_argument
# @click.option('--status/--no-status', default=True, help='Show status messages')
# @click.option('--stderr/--no-stderr', default=True, help='Show stderr messages')
# @click.option('--stdout/--no-stdout', default=True, help='Show stdout messages')
# @click.option('--stream/--no-stream', default=False, help='Watch and wait for new messages?')
# @click.option('--all/--no-all', default=False, help='Get all messages? This may take a while.')
# def logs(counter: str, status: bool, stderr: bool, stdout: bool, stream: bool, all: bool) -> None:
#     """
#     Show or stream execution event log.
#     """
#     project = get_project(require=True)
#     assert project
#     execution = project.get_execution_from_counter(counter=counter)
#     accepted_streams = {v for v in [
#         'status' if status else None,
#         'stderr' if stderr else None,
#         'stdout' if stdout else None,
#     ] if v}
#     lm = LogManager(execution)
#     limit = (0 if all else None)
#     while True:
#         events_response = lm.fetch_events(limit=limit)
#         events = events_response['events']
#         if not stream and events_response.get('truncated'):
#             warn(
#                 'There are {total} events, but only the last {n} are shown. Use `--all` to fetch everything.'.format(
#                     total=events_response['total'],
#                     n=len(events),
#                 )
#             )
#         for event in events:
#             if event['stream'] not in accepted_streams:
#                 continue
#             message = '{short_time} {text}'.format(
#                 short_time=(event['time'].split('T')[1][:-4]),
#                 text=clean_log_line(event['message']),
#             )
#             style = stream_styles.get(event['stream'], {})
#             click.echo(click.style(message, **style))  # type: ignore[arg-type]
#         if stream:
#             lm.update_execution()
#             if lm.execution['status'] in complete_execution_statuses:
#                 click.echo(
#                     'The execution has finished (status {status}); stopping stream.'.format(
#                         status=execution['status'],
#                     ),
#                     err=True
#                 )
#                 break
#             # Fetch less on subsequent queries
#             limit = 100
#             time.sleep(1)
#         else:
#             break


from tests.commands.execution.utils import get_execution_data_mock
from tests.fixture_data import EXECUTION_DATA
from valohai_cli.commands.execution.logs import logs


def test_logs(runner, logged_in_and_linked):
    counter = EXECUTION_DATA['counter']

    with get_execution_data_mock():
        output = runner.invoke(logs, [str(counter)], catch_exceptions=False).output
        assert 'temmie' in output and 'oh no' in output

# Path: tests/commands/execution/utils.py
# def get_execution_data_mock():
#     exec_id = EXECUTION_DATA['id']
#     datum_id = OUTPUT_DATUM_DATA['id']
#     m = requests_mock.mock()
#     project_id = PROJECT_DATA['id']
#     execution_counter = EXECUTION_DATA['counter']
#     m.get(f'{API_PREFIX}projects/{project_id}/', json=PROJECT_DATA)
#     m.get(f'{API_PREFIX}executions/', json={'results': [EXECUTION_DATA]})
#     m.get(f'{API_PREFIX}executions/{exec_id}/', json=EXECUTION_DATA)
#     m.get(f'{API_PREFIX}executions/{exec_id}/events/', json=EVENT_RESPONSE_DATA)
#     m.get(f'{API_PREFIX}data/?output_execution={exec_id}&limit=9000', json=OUTPUT_DATUM_RESPONSE_DATA)
#     m.get(f'{API_PREFIX}data/{datum_id}/download/', json=OUTPUT_DATUM_DOWNLOAD_RESPONSE_DATA)
#     execution_by_counter_url = f'{API_PREFIX}executions/{project_id}:{execution_counter}/'
#     m.get(url=get_startswith_re(execution_by_counter_url), json=EXECUTION_DATA)
#     m.delete(execution_by_counter_url, json={'ok': True})
#     m.post(re.compile('^https://app.valohai.com/api/v0/data/(.+?)/purge/$'), json={'ok': True})
#     return m
# 
# Path: tests/fixture_data.py
# EXECUTION_DATA = {
#     'counter': random.randint(1, 100),
#     'ctime': '2017-02-08T11:09:16.120102Z',
#     'id': execution_id,
#     'project': PROJECT_DATA,
#     'commit': {
#         'repository': 666,
#         'identifier': '000',
#         'ref': 'master',
#         'commit_time': '2017-02-15T08:46:58Z',
#         'url': 'https://app.valohai.com/api/v0/commits/7/'
#     },
#     'task': None,
#     'duration': 777,
#     'status': 'complete',
#     'step': 'run training',
#     'url': f'https://app.valohai.com/api/v0/executions/{execution_id}/',
#     'urls': {
#         'copy': 'https://app.valohai.com/api/v0/executions/34/copy/',
#         'display': 'https://app.valohai.com/p/test/mnist/execution/34/',
#         'stop': 'https://app.valohai.com/api/v0/executions/34/stop/',
#     },
#     'parameters': {
#         'dropout': 0.9,
#         'learning_rate': 0.001,
#         'max_steps': 300,
#     },
#     'outputs': [
#         OUTPUT_DATUM_DATA,
#     ],
#     'environment': {
#         'id': '88888888-8888-8888-8888-888888888888',
#         'name': 'local',
#         'owner': None,
#         'unfinished_job_count': 0,
#     },
#     'cumulative_metadata': {
#         'oispa': 'beer',
#     },
# }
# 
# Path: valohai_cli/commands/execution/logs.py
# @click.command()
# @counter_argument
# @click.option('--status/--no-status', default=True, help='Show status messages')
# @click.option('--stderr/--no-stderr', default=True, help='Show stderr messages')
# @click.option('--stdout/--no-stdout', default=True, help='Show stdout messages')
# @click.option('--stream/--no-stream', default=False, help='Watch and wait for new messages?')
# @click.option('--all/--no-all', default=False, help='Get all messages? This may take a while.')
# def logs(counter: str, status: bool, stderr: bool, stdout: bool, stream: bool, all: bool) -> None:
#     """
#     Show or stream execution event log.
#     """
#     project = get_project(require=True)
#     assert project
#     execution = project.get_execution_from_counter(counter=counter)
#     accepted_streams = {v for v in [
#         'status' if status else None,
#         'stderr' if stderr else None,
#         'stdout' if stdout else None,
#     ] if v}
#     lm = LogManager(execution)
#     limit = (0 if all else None)
#     while True:
#         events_response = lm.fetch_events(limit=limit)
#         events = events_response['events']
#         if not stream and events_response.get('truncated'):
#             warn(
#                 'There are {total} events, but only the last {n} are shown. Use `--all` to fetch everything.'.format(
#                     total=events_response['total'],
#                     n=len(events),
#                 )
#             )
#         for event in events:
#             if event['stream'] not in accepted_streams:
#                 continue
#             message = '{short_time} {text}'.format(
#                 short_time=(event['time'].split('T')[1][:-4]),
#                 text=clean_log_line(event['message']),
#             )
#             style = stream_styles.get(event['stream'], {})
#             click.echo(click.style(message, **style))  # type: ignore[arg-type]
#         if stream:
#             lm.update_execution()
#             if lm.execution['status'] in complete_execution_statuses:
#                 click.echo(
#                     'The execution has finished (status {status}); stopping stream.'.format(
#                         status=execution['status'],
#                     ),
#                     err=True
#                 )
#                 break
#             # Fetch less on subsequent queries
#             limit = 100
#             time.sleep(1)
#         else:
#             break


# Path: tests/commands/execution/test_logs.py
from tests.commands.execution.utils import get_execution_data_mock
from tests.fixture_data import EXECUTION_DATA
from valohai_cli.commands.execution.logs import logs



def test_logs(runner, logged_in_and_linked):
    counter = EXECUTION_DATA['counter']

    with get_execution_data_mock():
        output = runner.invoke(logs, [str(counter)], catch_exceptions=False).output
        assert 'temmie' in output and 'oh no' in output

        output = runner.invoke(logs, ['--no-stderr', str(counter)], catch_exceptions=False).output