<commit_before>#   Copyright 2018 The Batfish Open Source Project
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
import uuid
from os.path import abspath, dirname, join, pardir, realpath

import pytest
import requests
from requests.adapters import HTTPAdapter
from urllib3 import Retry

from pybatfish.client._diagnostics import (
    _INIT_INFO_QUESTIONS,
    _S3_BUCKET,
    _S3_REGION,
    upload_diagnostics,
)
from pybatfish.client.commands import (
    bf_delete_network,
    bf_delete_snapshot,
    bf_init_snapshot,
    bf_session,
    bf_set_network,
)
from pybatfish.question.question import QuestionBase

_this_dir = abspath(dirname(realpath(__file__)))
_root_dir = abspath(join(_this_dir, pardir, pardir))

_UPLOAD_MAX_TRIES = 3
_UPLOAD_RETRY_BACKOFF = 0.3


@pytest.fixture()
def network():
    name = bf_set_network()
    yield name
    # cleanup
    bf_delete_network(name)


@pytest.fixture()
def requests_session():
    # Setup a session with a retry policy
    session = requests.Session()
    # Prefix "http" will cover both "http" & "https"
    session.mount(
        "http",
        HTTPAdapter(
            max_retries=Retry(
                total=_UPLOAD_MAX_TRIES,
                backoff_factor=_UPLOAD_RETRY_BACKOFF,
                status_forcelist=[500, 502, 503, 504, 104],
            )
        ),
    )
    yield session


@pytest.fixture()
def example_snapshot(network):
    bf_set_network(network)
    name = uuid.uuid4().hex
    bf_init_snapshot(join(_this_dir, "snapshot"), name)
    yield name
    # cleanup
    bf_delete_snapshot(name)


def test_questions(network, example_snapshot):
    """Run diagnostic questions on example snapshot."""
    for template in _INIT_INFO_QUESTIONS:
        # Goal here is to run question successfully, i.e. not crash
        QuestionBase(template, bf_session).answer()


def test_upload_diagnostics(network, example_snapshot, requests_session):
    """Upload initialization information for example snapshot."""
    # This call raises an exception if any file upload results in HTTP status != 200
    resource = upload_diagnostics(
        session=bf_session, metadata={}, dry_run=False, resource_prefix="test/"<commit_msg>Tests: fix diagnostic retry (#698)<commit_after>#   Copyright 2018 The Batfish Open Source Project
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
import uuid
from os.path import abspath, dirname, join, pardir, realpath

import pytest
import requests
from requests.adapters import HTTPAdapter
from urllib3 import Retry

from pybatfish.client._diagnostics import (
    _INIT_INFO_QUESTIONS,
    _S3_BUCKET,
    _S3_REGION,
    upload_diagnostics,
)
from pybatfish.client.commands import (
    bf_delete_network,
    bf_delete_snapshot,
    bf_init_snapshot,
    bf_session,
    bf_set_network,
)
from pybatfish.question.question import QuestionBase

_this_dir = abspath(dirname(realpath(__file__)))
_root_dir = abspath(join(_this_dir, pardir, pardir))

_UPLOAD_MAX_TRIES = 3
_UPLOAD_RETRY_BACKOFF = 0.3


@pytest.fixture()
def network():
    name = bf_set_network()
    yield name
    # cleanup
    bf_delete_network(name)


@pytest.fixture()
def requests_session():
    # Setup a session with a retry policy
    session = requests.Session()
    adapter = HTTPAdapter(
        max_retries=Retry(
            total=_UPLOAD_MAX_TRIES,
            backoff_factor=_UPLOAD_RETRY_BACKOFF,
            status_forcelist=[500, 502, 503, 504, 104],
        )
    )
    # Override longest-match adapter for http and https
    session.mount(
        "http://", adapter,
    )
    session.mount(
        "https://", adapter,
    )
    yield session


@pytest.fixture()
def example_snapshot(network):
    bf_set_network(network)
    name = uuid.uuid4().hex
    bf_init_snapshot(join(_this_dir, "snapshot"), name)
    yield name
    # cleanup
    bf_delete_snapshot(name)


def test_questions(network, example_snapshot):
    """Run diagnostic questions on example snapshot."""
    for template in _INIT_INFO_QUESTIONS:
        # Goal here is to run question successfully, i.e. not crash
        QuestionBase(template, bf_session).answer()


def test_upload_diagnostics(network, example_snapshot, requests_session):
    """Upload initialization information for example snapshot."""
    # This call raises an exception if any file upload results in HTTP status != 200
    resource = upload_diagnostics(
        session=bf_session, metadata={}, dry_run=False, resource_prefix="test/"
{'fraction_non_alphanumeric': 0.08052468573510657, 'fraction_numerical': 0.012570595736928402, 'mean_word_length': 3.6173254835996635, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 1, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3614412', 'n_tokens_mistral': 1693, 'n_tokens_neox': 1657, 'n_words': 500}