import requests
import json
import os

SCENARIOS_PATH = "scenarios/";

class Test:

    def __init__(self):
        self.scenarios = []

    def run(self):
        for scenario in self.scenarios:
            if scenario.get("method") == "GET":
                self.send_get_request(scenario)
            elif scenario.get("method") == "POST":
                self.send_post_request(scenario)
            else:
                print "Skipping ", scenario["name"], " please specify request method."

    def load_test_scenarios(self, scenarios_path):
        scenario_names = [scenario_file for scenario_file in os.listdir(scenarios_path) if scenario_file.endswith('.json')]
        for scenario_name in scenario_names:
            with open(os.path.join(scenarios_path, scenario_name)) as scenario_file:
                self.scenarios.append(json.load(scenario_file))

    def send_get_request(self, scenario):
        if scenario.get("user"):
            auth = (scenario["user"]["login"], scenario["user"]["password"])
        else:
            auth = None

        try:
            res = requests.get(scenario["url"], auth=auth)
        except Exception:
             print "Test {0} failed!".format(scenario["name"])
             return

        if res.status_code == 200:
            if scenario.get("expected_output") != None:
                if scenario.get("expected_output") == res.json():
                        print "Test {0} OK!".format(scenario["name"])
                else:
                        print "Test {0}, expected {1} but got {2}!".format(scenario["name"],
                            scenario["expected_output"], res.json())
            else:
                print "Test {0} OK!".format(scenario["name"])
        else:
            print "Test {0} failed!".format(scenario["name"])

    def send_post_request(self, scenario):
        if scenario.get("user"):
            auth = (scenario["user"]["login"], scenario["user"]["password"])
        else:
            auth = None

        res = requests.post(scenario["url"], auth=auth, data=scenario.get("payload"))

        if res.status_code == 200:
            if scenario.get("expected_output") != None:
                if scenario.get("expected_output") == res.json():
                        print "Test {0} OK!".format(scenario["name"])
                else:
                        print "Test {0}, expected {1} but got {2}!".format(scenario["name"],
                            scenario["expected_output"], res.json())
            else:
                print "Test {0} OK!".format(scenario["name"])
        else:
            print "Test {0} failed!".format(scenario["name"])


file_path = os.path.join(os.path.dirname(__file__), SCENARIOS_PATH)

test = Test()
test.load_test_scenarios(file_path)
test.run()
