from collections import Counter

import pytest

from endpoints.api.test.shared import client_with_identity, conduct_api_call
from endpoints.api.signing import RepositorySignatures
from test.fixtures import app, appconfig, database_uri, init_db_path, sqlitedb_file
from mock import patch

VALID_TARGETS = {
  'latest': {
    'hashes': {
      'sha256': 'mLmxwTyUrqIRDaz8uaBapfrp3GPERfsDg2kiMujlteo='
    },
    'length': 1500
  },
  'test_tag': {
    'hashes': {
      'sha256': '1234123'
    },
    'length': 50
  }
}

def tags_equal(expected, actual):
  expected_tags = expected.get('tags')
  actual_tags = actual.get('tags')
  if expected_tags and actual_tags:
    return Counter(expected_tags) == Counter(actual_tags)
  return expected == actual

@pytest.mark.parametrize('targets,expected', [
  (VALID_TARGETS, {'tags': VALID_TARGETS, 'expiration': 'expires'}),
  ({'bad': 'tags'}, {'tags': {'bad': 'tags'}, 'expiration': 'expires'}),
  ({}, {'tags': {}, 'expiration': 'expires'}),
  (None, {'tags': None, 'expiration': 'expires'}),   # API returns None on exceptions
])
def test_get_signatures(targets, expected, client):
  with patch('endpoints.api.signing.tuf_metadata_api') as mock_tuf:
    mock_tuf.get_default_tags_with_expiration.return_value = (targets, 'expires')
    with client_with_identity('devtable', client) as cl:
      params = {'repository': 'devtable/trusted'}
      assert tags_equal(expected, conduct_api_call(cl, RepositorySignatures, 'GET', params, None, 200).json)