# Copyright 2020 OpenStack Foundation
#
# 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 json
import time
import urllib3


testinfra_hosts = ['refstack01.openstack.org']

test_result_json = {
    "cpid": "9cddf99456964d7c90b98362e7175a12",
    "duration_seconds": 10,
    "results": [
        {
            "name": "tempest.api.compute.flavors.test_flavors."
                    "FlavorsV2TestJSON.test_list_flavors",
            "uuid": "e36c0eaa-dff5-4082-ad1f-3f9a80aa3f59"
        }
    ]
}


def test_refstack_listening(host):
    # Give it some time to come up
    for i in range(300):
        refstack_https = host.socket("tcp://0.0.0.0:443")
        if refstack_https.is_listening:
            break
        time.sleep(1)
    assert refstack_https.is_listening
    refstack_http = host.socket("tcp://0.0.0.0:8000")
    assert refstack_http.is_listening

def test_refstack_container_running(host):
    cmd = host.run("docker inspect refstack-docker_refstack-api_1")
    out = json.loads(cmd.stdout)
    assert out[0]["State"]["Status"] == "running"
    assert out[0]["RestartCount"] == 0

def test_refstack_result_submission(host):
    url = "https://refstack01.openstack.org/v1/results/"
    headers = {'Content-type': 'application/json'}
    data = json.dumps(test_result_json)
    http = urllib3.PoolManager(cert_reqs='CERT_NONE')
    resp = http.request('POST', url, body=data, headers=headers)
    assert resp.status == 201