<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Filename: expectation.py

import json

from .error import RestTestError
from .colortext import ColorText
from ..utils import utils


class Expectation():
    """docstring for Expectation"""

    SUPPORTED_TYPE = \
        ('status_code', 'include_keys', 'include_words', 'value')
    ATTRIBUTES = ('value', 'obj', 'left', 'op', 'right')
    SUPPORTED_OPERATORS = {
        '=': 'eq',
        '!=': 'ne',
        '>': 'gt',
        '>=': 'ge',
        '<': 'lt',
        '<=': 'le',
        'in': 'in'
    }
    count = 0
    successed = 0

    def __init__(self, doc, response):
        if not isinstance(doc, dict):
            raise RestTestError('FORMAT_ERROR', correct_type='dict')
        if 'type' not in doc.keys():
            raise RestTestError('KEY_NOT_FOUND', key='type', collection=doc)
        if doc['type'] not in self.SUPPORTED_TYPE:
            raise RestTestError('UNSUPPORT_METHOD', method=doc['type'])
        if not response:
            raise RestTestError('NO_RESPONSE')

        self.type = doc['type']
        for attr in self.ATTRIBUTES:
            if attr in doc.keys():
                setattr(self, attr, doc[attr])
            else:
                setattr(self, attr, None)

        self.response = response

    def check_expectation(self):
        method_name = 'check_' + self.type
        mtd = getattr(self, method_name)
        return mtd()

    def check_status_code(self):
        if not self.value:
            raise RestTestError('SOMETHING_MISSING', sth='expect value')

        if str(self.response.status_code) == str(self.value):
            self.print_result('SUCCESS')
        else:
            self.print_result('FAIL', 'get status code {0}'.format(
                            self.response.status_code))

    def check_include_keys(self):
        if not self.value or not self.obj:
            raise RestTestError('SOMETHING_MISSING',
                                sth='value or obj')

        for key in self.value:
            json_value = self.get_json()
            if isinstance(json_value, dict) and key in json_value.keys():
                self.print_result('SUCCESS', key=key)
            elif isinstance(json_value, list):
                has_key = True
                for item in json_value:
                    if key not in item.keys():
                        has_key = False
                        break
                if has_key:
                    self.print_result('SUCCESS', key=key)
            else:
                self.print_result('FAIL', key=key)

    def check_include_words(self):
        if not self.value or not self.obj:
            raise RestTestError('SOMETHING_MISSING',
                                sth='value or obj')

        for word in self.value:
            json_value = self.get_json()
            text = json.dumps(json_value, ensure_ascii=False)
            if word in text:
                self.print_result('SUCCESS', word=word)
            else:
                self.print_result('FAIL', word=word)

    def check_value(self):
        if self.left is None or self.right is None or not self.op \
                or not self.obj:
            raise RestTestError('SOMETHING_MISSING',
                                sth='left, right, obj or op')
        if self.op not in self.SUPPORTED_OPERATORS.keys():
            raise RestTestError('UNSUPPORT_OPERATOR',
                                operator=self.op)

        if self.pass_expression():
            self.print_result('SUCCESS')
        else:
            self.print_result('FAIL')

    def print_result(self, result, msg=None, **params):
        ''' print_result
            this function is to print suitable result for expectation check
            pass 'SUCCESS' OR 'FAIL' as result
            pass fail message as msg
            msg only work in 'FAIL' type
            params used to print statement info
        '''
        result_type = ('SUCCESS', 'FAIL')
        if result not in result_type:
            raise RestTestError('UNSUPPORT_TYPE', type=result,
                                whenclause='print expectation result')

        # print expectation statement
        Expectation.count += 1
        utils.print_log(ColorText('checking expectation: No.{}'.format(
            str(Expectation.count)), 'purple'))
        m_statement = '{} should {}'

        e_type = e_value = None
        if self.type == 'status_code':
            e_type = ColorText('status code', 'yellow')
            e_value = ColorText('be ' + str(self.value), 'yellow')
        if self.type == 'include_keys':
            e_type = ColorText(params['key'], 'yellow')
            e_value = ColorText('in ' + str(self.obj), 'yellow')
        if self.type == 'include_words':
            e_type = ColorText(params['word'], 'yellow')
            e_value = ColorText('in ' + str(self.obj), 'yellow')
        if self.type == 'value':
            e_type = ColorText(str(self.left), 'yellow')<commit_msg>refine output words<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Filename: expectation.py

import json

from .error import RestTestError
from .colortext import ColorText
from ..utils import utils


class Expectation():
    """docstring for Expectation"""

    SUPPORTED_TYPE = \
        ('status_code', 'include_keys', 'include_words', 'value')
    ATTRIBUTES = ('value', 'obj', 'left', 'op', 'right')
    SUPPORTED_OPERATORS = {
        '=': 'eq',
        '!=': 'ne',
        '>': 'gt',
        '>=': 'ge',
        '<': 'lt',
        '<=': 'le',
        'in': 'in'
    }
    count = 0
    successed = 0

    def __init__(self, doc, response):
        if not isinstance(doc, dict):
            raise RestTestError('FORMAT_ERROR', correct_type='dict')
        if 'type' not in doc.keys():
            raise RestTestError('KEY_NOT_FOUND', key='type', collection=doc)
        if doc['type'] not in self.SUPPORTED_TYPE:
            raise RestTestError('UNSUPPORT_METHOD', method=doc['type'])
        if not response:
            raise RestTestError('NO_RESPONSE')

        self.type = doc['type']
        for attr in self.ATTRIBUTES:
            if attr in doc.keys():
                setattr(self, attr, doc[attr])
            else:
                setattr(self, attr, None)

        self.response = response

    def check_expectation(self):
        method_name = 'check_' + self.type
        mtd = getattr(self, method_name)
        return mtd()

    def check_status_code(self):
        if not self.value:
            raise RestTestError('SOMETHING_MISSING', sth='expect value')

        if str(self.response.status_code) == str(self.value):
            self.print_result('SUCCESS')
        else:
            self.print_result('FAIL', 'get status code {0}'.format(
                            self.response.status_code))

    def check_include_keys(self):
        if not self.value or not self.obj:
            raise RestTestError('SOMETHING_MISSING',
                                sth='value or obj')

        for key in self.value:
            json_value = self.get_json()
            if isinstance(json_value, dict) and key in json_value.keys():
                self.print_result('SUCCESS', key=key)
            elif isinstance(json_value, list):
                has_key = True
                for item in json_value:
                    if key not in item.keys():
                        has_key = False
                        break
                if has_key:
                    self.print_result('SUCCESS', key=key)
            else:
                self.print_result('FAIL', key=key)

    def check_include_words(self):
        if not self.value or not self.obj:
            raise RestTestError('SOMETHING_MISSING',
                                sth='value or obj')

        for word in self.value:
            json_value = self.get_json()
            text = json.dumps(json_value, ensure_ascii=False)
            if word in text:
                self.print_result('SUCCESS', word=word)
            else:
                self.print_result('FAIL', word=word)

    def check_value(self):
        if self.left is None or self.right is None or not self.op \
                or not self.obj:
            raise RestTestError('SOMETHING_MISSING',
                                sth='left, right, obj or op')
        if self.op not in self.SUPPORTED_OPERATORS.keys():
            raise RestTestError('UNSUPPORT_OPERATOR',
                                operator=self.op)

        if self.pass_expression():
            self.print_result('SUCCESS')
        else:
            self.print_result('FAIL')

    def print_result(self, result, msg=None, **params):
        ''' print_result
            this function is to print suitable result for expectation check
            pass 'SUCCESS' OR 'FAIL' as result
            pass fail message as msg
            msg only work in 'FAIL' type
            params used to print statement info
        '''
        result_type = ('SUCCESS', 'FAIL')
        if result not in result_type:
            raise RestTestError('UNSUPPORT_TYPE', type=result,
                                whenclause='print expectation result')

        # print expectation statement
        Expectation.count += 1
        utils.print_log(ColorText('checking expectation: No.{}'.format(
            str(Expectation.count)), 'purple'))
        m_statement = '{} should {}'

        e_type = e_value = None
        if self.type == 'status_code':
            e_type = ColorText('status code', 'yellow')
            e_value = ColorText('be ' + str(self.value), 'yellow')
        if self.type == 'include_keys':
            e_type = ColorText('key ' + params['key'], 'yellow')
            e_value = ColorText('in ' + str(self.obj), 'yellow')
        if self.type == 'include_words':
            e_type = ColorText('word ' + params['word'], 'yellow')
            e_value = ColorText('in ' + str(self.obj), 'yellow')
        if self.type == 'value':
            e_type = ColorText(str(self.left), 'yellow')
{'fraction_non_alphanumeric': 0.1155033356566763, 'fraction_numerical': 0.0009957184108334164, 'mean_word_length': 1.823727860556649, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1529518', 'n_tokens_mistral': 2868, 'n_tokens_neox': 2751, 'n_words': 713}