import json
import io
import Intel471MalwareIndicator as feed


def util_load_json(path):
    with io.open(path, mode='r', encoding='utf-8') as f:
        return json.loads(f.read())


def test_build_relationships():
    """
    Given:
        - relationships configuration.
    When:
        - getting indicators feed.
    Then:
        - validate the relationships is created correctly.
    """
    type_ = 'url'
    value_ = 'http://example_url.com'
    malware_family = 'test-malware'

    res = feed.build_relationships(type_, value_, malware_family)

    assert res[0] == {'entityA': 'http://example_url.com', 'entityAFamily': 'Indicator', 'entityAType': 'url',
                      'entityB': 'test-malware', 'entityBFamily': 'Indicator', 'entityBType': 'Malware',
                      'fields': {}, 'name': 'indicator-of', 'reverseName': 'indicated-by',
                      'type': 'IndicatorToIndicator'}


def test_fetch_indicators(requests_mock, mocker):
    """Tests the fetch-indicators command function.

    Configures requests_mock instance to generate the appropriate
    get_indicator API response, loaded from a local JSON file. Checks
    the output of the command function with the expected output.
    """
    from Intel471MalwareIndicator import Client, fetch_indicators

    mock_indicators_response = util_load_json('test_data/search_indicators.json')
    requests_mock.get(
        'https://api.intel471.com/v1/indicators/stream',
        json=mock_indicators_response)

    client = Client(auth=('username', 'apikey'), fetch_time="3 days")

    girs = [
        {
            "uid": "d42bee57ea536afbe19fdfb1d563a516",
            "data": {
                "gir": {
                    "path": "1.1.6",
                    "name": "Loader malware",
                    "description": "Description of loader malware.",
                    "parent": {
                        "path": "1.1",
                        "name": "Malware variants",
                        "description": "Description of malware variants.",
                        "parent": {
                            "path": "1",
                            "name": "Malware",
                            "description": "Description of malware."
                        }
                    }
                }
            }
        }
    ]

    mocker.patch.object(client, 'get_girs', return_value=girs)

    assert fetch_indicators(
        client=client,
        save_state=False,
        limit=1
    )
