<file_sep>#!/usr/bin/env python3
import os
import venv
from pathlib import Path
import sys
testSuit = sys.argv[1]
root_path = Path(__file__).parent.resolve()
venv_dir = root_path / '.venv'


def runner():
    if not venv_dir.exists():
        try:
            venv.create(venv_dir, with_pip=True)
        except SystemError:
            print("Virtualenv was NOT created")
        finally:
            print("Virtualenv was created")
        if venv_dir.exists():
            try:
                os.system("pip install -r requirements.txt")
            except SystemError:
                print("Requirements were NOT installed")
            finally:
                print("Requirements were installed")
    elif venv_dir.exists():
        try:
            os.system("python -m robot.run --outputdir logs_folder " + testSuit)
        except SystemError:
            print("Tests were not started")
        finally:
            print("Finish!")

if __name__ == "__main__":
    runner()<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -
import random
from datetime import timedelta

from faker import Factory
from faker.providers.company.en_US import Provider as CompanyProviderEnUs
from faker.providers.company.ru_RU import Provider as CompanyProviderRuRu
from munch import munchify

from data.op_faker.op_faker import OP_Provider
from local_time import get_now

fake_en = Factory.create(locale='en_US')
fake_ru = Factory.create(locale='ru_RU')
fake_uk = Factory.create(locale='uk_UA')
fake_uk.add_provider(OP_Provider)
fake = fake_uk
used_identifier_id = []
mode_open =     ["belowThreshold", "aboveThresholdUA", "aboveThresholdEU",
                "aboveThresholdUA.defense", "competitiveDialogueUA", "competitiveDialogueEU", "esco"]
mode_limited =  ["reporting", "negotiation.quick", "negotiation"]
violationType = ["corruptionDescription", "corruptionProcurementMethodType", "corruptionChanges",
                "corruptionPublicDisclosure", "corruptionBiddingDocuments", "documentsForm",
                "corruptionAwarded", "corruptionCancelled", "corruptionContracting"]

# This workaround fixes an error caused by missing "catch_phrase" class method
# for the "ru_RU" locale in Faker >= 0.7.4
fake_ru.add_provider(CompanyProviderEnUs)
fake_ru.add_provider(CompanyProviderRuRu)


def create_fake_sentence():
    return fake.sentence(nb_words=10, variable_nb_words=True)


def create_fake_funder():
    return fake.funders_data()


def get_fake_funder_scheme():
    return fake.funder_scheme()


def create_fake_amount(award_amount):
    return round(random.uniform(1, award_amount), 2)


def create_fake_number(min_number, max_number):
    return random.randint(int(min_number), int(max_number))


def create_fake_float(min_number, max_number):
    return random.uniform(float(min_number), float(max_number))


def create_fake_title():
    return u"[ТЕСТУВАННЯ] {}".format(fake.title())


def create_fake_date():
    return get_now().isoformat()


def create_fake_period(days=0, hours=0, minutes=0):
    data = {
        "startDate": get_now().isoformat(),
        "endDate": (get_now() + timedelta(days=days, hours=hours, minutes=minutes)).isoformat()
    }
    return data


def subtraction(value1, value2):
    if "." in str (value1) or "." in str (value2):
        return (float (value1) - float (value2))
    else:
        return (int (value1) - int (value2))


def create_fake_value_amount():
    return fake.random_int(min=1)


def get_number_of_minutes(days, accelerator):
    return 1440 * int(days) / accelerator


def field_with_id(prefix, sentence):
    return u"{}-{}: {}".format(prefix, fake.uuid4()[:8], sentence)


"""Method for data criteria"""



def data_for_criteria(scheme='ДК021'):
    data = fake.fake_item(scheme)
    data_json = munchify(
        {
            "name": fake_uk.name(),
            "nameEng": fake_en.name(),
            "classification": {
                "id": data["classification"]["id"],
                "scheme": "ДК021",
                "description": data["classification"]["description"]
            },
            "additionalClassification": {
                "id": data["additionalClassifications"][0]["id"],
                "scheme": data["additionalClassifications"][0]["scheme"],
                "description": data["additionalClassifications"][0]["description"],
            },
            "minValue": str(create_fake_float(0, 10)),
            "maxValue": str(create_fake_float(11, 42)),
            "dataType": random.choice(['number', 'integer', 'boolean', 'string']),
            "unit": {
                "name": data['unit']['name'],
                "code": data['unit']['code']
            }
        }
    )
    return data_json


def data_for_edit():
    data = munchify(
        {
            "name": fake_uk.name(),
            "nameEng": fake_en.name(),
            "minValue": str(create_fake_float(0, 22)),
            "maxValue": str(create_fake_float(43, 54)),
            "status": "active"
        }
    )
    return data
<file_sep>from data.op_faker import *<file_sep>import os
from munch import Munch, munchify
from json import load, loads


def load_data_from(file_name):
    """We assume that 'external_params' is a a valid json if passed
    """

    if not os.path.exists(file_name):
        file_name = os.path.join(os.path.dirname(__file__), 'data', file_name)
    with open(file_name) as file_obj:
        if file_name.endswith('.json'):
            file_data = Munch.fromDict(load(file_obj))
        elif file_name.endswith('.yaml'):
            file_data = Munch.fromYAML(file_obj)

    return munchify(file_data)<file_sep>from http.client import BadStatusLine
from client.criteria_client import ClientCriteria
from retrying import retry


def retry_if_request_failed(exception):
    status_code = getattr(exception, 'status_code', None)
    print(status_code)
    if 500 <= status_code < 600 or status_code in (409, 429, 412):
        return True
    else:
        return isinstance(exception, BadStatusLine)


class StableClient(ClientCriteria):
    @retry(stop_max_attempt_number=100, wait_random_min=500,
           wait_random_max=4000, retry_on_exception=retry_if_request_failed)
    def request(self, *args, **kwargs):
        return super(StableClient, self).request(*args, **kwargs)



def prepare_api_wrapper(username, password, api_host, api_version):
    return StableClient(username, password, api_host, api_version)<file_sep>#!/usr/bin/python
import os
import json
from json import loads
import asyncio
import requests
from munch import munchify
from requests.auth import HTTPBasicAuth

from client.exceptions import InvalidResponse


class ClientCriteria(object):
    def __init__(self, username='', password='', api_host='http://localhost:8000',
                 api_version='0', loop=asyncio.get_event_loop()):
        self._username = username
        self._password = <PASSWORD>
        self.api_host = api_host
        self.api_version = api_version
        self.loop = loop
        self.url = api_host + '/api/' + api_version + '/'
        self.headers = {'Content-Type': 'application/json'}

    #######Method GET####################

    def get_criteria(self, path='', criteria_id=None):
        if isinstance(criteria_id, type(None)):
            response = requests.get(
                url=self.url + path + '/',
                auth=HTTPBasicAuth(self._username, self._password),
                headers=self.headers
            )
        else:
            response = requests.get(
                url=self.url + path + '/' + criteria_id + '/',
                auth=HTTPBasicAuth(self._username, self._password),
                headers=self.headers,
            )
        if response.status_code == 200:
            return munchify(loads(response.text))
        raise InvalidResponse(response)

    def get_status(self, path='', status_path=None):
        response = requests.get(
            url=self.url + path + '/' + status_path,
            auth=HTTPBasicAuth(self._username, self._password),
            headers=self.headers,
        )
        if response.status_code == 200:
            return munchify(loads(response.text))
        raise InvalidResponse(response)

    ######Method POST########################

    def create_criteria(self, path='', data={}):
        response = requests.post(
            url=self.url + path + '/',
            auth=HTTPBasicAuth(self._username, self._password),
            data=json.dumps(data),
            headers=self.headers
        )
        if response.status_code == 201:
            return munchify(loads(response.text))
        raise InvalidResponse(response)

    ##############Method PATCH#############

    def update_criteria(self, criteria_id, path='', data={}):
        response = requests.patch(
            url=self.url + path + '/' + criteria_id + '/',
            auth=HTTPBasicAuth(self._username, self._password),
            headers=self.headers,
            data=json.dumps(data)
        )
        if response.status_code == 200:
            return munchify(loads(response.text))
        raise InvalidResponse(response)

    ##########Method DELETE###################

    def delete_criteria(self, criteria_id, path=''):
        response = requests.delete(
            url=self.url + path + '/' + criteria_id + '/',
            auth=HTTPBasicAuth(self._username, self._password),
            headers=self.headers
        )
        if response.status_code == 200:
            return response.status_code
        raise InvalidResponse(response)
<file_sep>certifi==2019.11.28
chardet==3.0.4
Faker==3.0.0
idna==2.8
munch==2.5.0
python-dateutil==2.8.1
pytz==2019.3
PyYAML==5.2
requests==2.22.0
retrying==1.3.3
robotframework==3.1.2
six==1.13.0
text-unidecode==1.3
urllib3==1.25.7
<file_sep># -*- coding: utf-8 -*-
from faker.generator import random
from faker.providers import BaseProvider
from copy import deepcopy
from munch import Munch
import random
from json import load
import os


def load_data_from_file(file_name):
    if not os.path.exists(file_name):
        file_name = os.path.join(os.path.dirname(__file__), file_name)
    with open(file_name) as file_obj:
        if file_name.endswith(".json"):
            return Munch.fromDict(load(file_obj))
        elif file_name.endswith(".yaml"):
            return Munch.fromYAML(file_obj)


class OP_Provider(BaseProvider):
    _fake_data = load_data_from_file("op_faker_data.json")
    word_list = _fake_data.words
    procuringEntities = _fake_data.procuringEntities
    funders = _fake_data.funders
    funders_scheme_list = _fake_data.funders_scheme
    addresses = _fake_data.addresses
    classifications = _fake_data.classifications
    cpvs = _fake_data.cpvs
    moz_cpvs = _fake_data.moz_cpvs
    items_base_data = _fake_data.items_base_data
    rationale_types = _fake_data.rationale_types
    units = _fake_data.units

    @classmethod
    def randomize_nb_elements(self, number=10, le=60, ge=140):
        """
        Returns a random value near number.

        :param number: value to which the result must be near
        :param le: lower limit of randomizing (percents). Default - 60
        :param ge: upper limit of randomizing (percents). Default - 140
        :returns: a random int in range [le * number / 100, ge * number / 100]
            with minimum of 1
        """
        if le > ge:
            raise Exception("Lower bound: {} is greater then upper: {}.".format(le, ge))
        return int(number * self.random_int(min=le, max=ge) / 100) + 1

    @classmethod
    def word(self):
        """
        :example 'Курка'
        """
        return self.random_element(self.word_list)

    @classmethod
    def words(self, nb=3):
        """
        Generate an array of random words
        :example: array('Надіньте', 'фуражка', 'зелено')
        :param nb: how many words to return
        """
        return random.sample(self.word_list, nb)

    @classmethod
    def sentence(self, nb_words=5, variable_nb_words=True):
        """
        Generate a random sentence
        :example: 'Курка надіньте пречудовий зелено на.'
        :param nb_words: how many words the sentence should contain
        :param variable_nb_words: set to false if you want exactly $nbWords returned,
            otherwise $nbWords may vary by +/-40% with a minimum of 1
        """
        if nb_words <= 0:
            return ''

        if variable_nb_words:
            nb_words = self.randomize_nb_elements(number=nb_words)

        words = self.words(nb_words)
        words[0] = words[0].title()

        return " ".join(words) + '.'

    @classmethod
    def title(self):
        return self.sentence(nb_words=3)

    @classmethod
    def description(self):
        return self.sentence(nb_words=10)

    @classmethod
    def procuringEntity(self):
        return deepcopy(self.random_element(self.procuringEntities))

    @classmethod
    def funders_data(self):
        return self.random_element(self.funders)

    @classmethod
    def funder_scheme(self):
        return self.random_element(self.funders_scheme_list)

    @classmethod
    def cpv(self, cpv_group=None):
        if cpv_group:
            cpvs = []
            for cpv_element in self.cpvs:
                if cpv_element.startswith(cpv_group):
                    cpvs.append(cpv_element)
            return self.random_element(cpvs)
        else:
            return self.random_element(self.cpvs)


    @classmethod
    def fake_item(self, scheme_group):
        # """
        # Generate a random item for criteria
        scheme_group = str(scheme_group)
        similar_scheme = []
        actual_schema = ['ДК021', 'CPV_EN', 'CPV_RU', 'ДК003', ' ДК015', 'ДК018', 'КЕКВ', 'NONE', 'specialNorms', 'UA-ROAD', 'GMDN']

        for scheme_element in self.classifications:
            if scheme_element["classification"]["scheme"].startswith(scheme_group) \
                    and scheme_element["additionalClassifications"][0]["scheme"] in actual_schema \
                    and len(scheme_element["additionalClassifications"][0]["id"]) <= 10:
                similar_scheme.append(scheme_element)
        scheme = random.choice(similar_scheme)

        similar_units = []
        for unit_element in self.units:
            similar_units.append(unit_element)
        unit = random.choice(similar_units)

        data = dict(scheme)
        data['unit'] = unit

        return deepcopy(data)<file_sep>##  ДЛЯ ЗАПУСКУ ТЕСТІВ ПОТРІБНО ЗРОБИТИ НАСТУПНІ КРОКИ:
### 1. КЛОНУВАТИ РЕПОЗИТОРІЙ 
    * Прописати в консолі: git clone https://github.com/orest77/eCatalogues_tests.git
### 2. Для запуску тестового сценарію потрібно:
    * Надати права файлу <run_test.py> (прописати в консолі sudo chmod -x run_test.py)
    * Запустити тести ./run_test.py e_catalogues_tests.robot 
### 3. ТАКОЖ МОЖНА  НЕ  ВИКОНУВАТИ  2  ПУНКТУ  ЗАПУСТИВШИ ТЕСТИ КОМАНДОЮ 
    *  python3 -m run_test.py e_catalogues_tests.robot