import demistomock as demisto


def test_fetch_indicators_main(mocker):
    """
    Given
    - indicators response from malware bazzar feed

    When
    - Running main flow for fetching indicators command

    Then
    - Ensure that all indicators values exist and are not 'None'
    """
    from MalwareBazaarFeed import main
    from JSONFeedApiModule import Client

    mocker.patch.object(
        demisto, 'params', return_value={
            'feed': True, 'feedBypassExclusionList': False, 'feedExpirationInterval': '20160',
            'feedExpirationPolicy': 'suddenDeath', 'feedFetchInterval': 1,
            'feedReliability': 'A - Completely reliable', 'feedReputation': 'None', 'feedTags': None,
            'insecure': True, 'ip_ranges': 'All available Google IP ranges', 'proxy': False, 'tlp_color': None,
            'url': 'https://mb-api.abuse.ch'
        }
    )
    mocker.patch.object(demisto, 'command', return_value='fetch-indicators')
    create_indicators_mocker = mocker.patch.object(demisto, 'createIndicators')

    mocker.patch.object(
        Client, 'build_iterator', side_effect=[
            (
                [{'sha256_hash': '1234'}, {'sha256_hash': '12345'}, {'sha256_hash': '123456'}],
                True
            ),
            (
                [],
                True
            )
        ]
    )

    main()

    assert create_indicators_mocker.call_args.args[0] == [
        {
            'type': 'File', 'fields': {'tags': [], 'downloadurl': 'https://bazaar.abuse.ch/sample/1234/'},
            'value': '1234', 'rawJSON': {'sha256_hash': '1234'}
        },
        {
            'type': 'File', 'fields': {'tags': [], 'downloadurl': 'https://bazaar.abuse.ch/sample/12345/'},
            'value': '12345', 'rawJSON': {'sha256_hash': '12345'}
        },
        {
            'type': 'File', 'fields': {'tags': [], 'downloadurl': 'https://bazaar.abuse.ch/sample/123456/'},
            'value': '123456', 'rawJSON': {'sha256_hash': '123456'}
        }
    ]


def test_custom_build_relationships():
    """
    Given
    - no feed config

    When
    - Running custom_build_relationships function

    Then
    - Ensure the relationship list is empty
    """
    from MalwareBazaarFeed import custom_build_relationships

    assert custom_build_relationships(feed_config={}, _mapping={}, indicator_data={}) == []


def test_custom_mapping_function():
    """
    Given
    - mapping, attributes and indicators

    When
    - Running custom_mapping_function function

    Then
    - Ensure indicator dict is updated
    """
    from MalwareBazaarFeed import custom_mapping_function
    mapping = {'a': 'a.b', 'c': 'c', 'd': 'd'}
    attributes = {'a': 'a', 'b': 'b', 'c': 'c'}
    indicator = {'fields': {'a': [{'a': 'a'}], 'b': 'b'}}

    custom_mapping_function(mapping, indicator, attributes)

    assert indicator == {'fields': {'a': [{'a': 'a', 'b': 'a'}], 'b': 'b', 'c': 'c'}}
