Ejemplo n.º 1
0
    def validate(self, document):
        """Validate input.

        Arguments:
            document -- Input stream to validate.

        Raises:
            ValidationError: When the number is not a digit.
            ValidationError: When the length is > 8 digits.
        """
        text = document.text

        if text and not text.isdigit():
            i = 0

            # Get index of fist non numeric character.
            # We want to move the cursor here.
            for i, value in enumerate(text):
                if not value.isdigit():
                    break

            raise ValidationError(message='Input is not a number',
                                  cursor_position=i)
        if text and not len(text) == 8:
            i = 0

            # Get index of fist non numeric character.
            # We want to move the cursor here.
            for i, value in enumerate(text):
                if not value.isdigit():
                    break

            raise ValidationError(message='This input is not 8 digits long.',
                                  cursor_position=i)
Ejemplo n.º 2
0
    def validate(self, document):
        """
        Check input for Python syntax errors.
        """
        # When the input starts with Ctrl-Z, always accept. This means EOF in a
        # Python REPL.
        if document.text.startswith('\x1a'):
            return

        try:
            if self.get_compiler_flags:
                flags = self.get_compiler_flags()
            else:
                flags = 0

            compile(document.text, '<input>', 'exec', flags=flags, dont_inherit=True)
        except SyntaxError as e:
            # Note, the 'or 1' for offset is required because Python 2.7
            # gives `None` as offset in case of '4=4' as input. (Looks like
            # fixed in Python 3.)
            index = document.translate_row_col_to_index(e.lineno - 1,  (e.offset or 1) - 1)
            raise ValidationError(index, 'Syntax Error')
        except TypeError as e:
            # e.g. "compile() expected string without null bytes"
            raise ValidationError(0, str(e))
        except ValueError as e:
            # In Python 2, compiling "\x9" (an invalid escape sequence) raises
            # ValueError instead of SyntaxError.
            raise ValidationError(0, 'Syntax Error: %s' % e)
Ejemplo n.º 3
0
 def validate(self, document: Document) -> bool:
     if document.text == "":
         raise ValidationError(message="an existing file name is required")
     path = os.path.join(self.basedir, document.text)
     if os.path.exists(path):
         return True
     raise ValidationError(message=path + " file does not exist")
Ejemplo n.º 4
0
def run_subvalidator(text):
    """Checks if the run statement is properly formatted

    Parameters
    ----------
    text : str
        input statement

    """
    valid_keywords = ['logger', 'threads']
    valid_logger_values = ['csv', 'sqlite']
    kwargs = dict(
        [kwarg.split('=') for kwarg in text.split(None)[1:] if '=' in kwarg])
    for k, val in kwargs.items():
        if k not in valid_keywords:
            pos = list(re.finditer(k, text))[0].end()
            raise ValidationError(
                message='{} not a valid keyword'.format(k),
                cursor_position=pos,
            )
        else:
            if k == 'logger' and val not in valid_logger_values:
                pos = list(re.finditer(val, text))[0].end()
                raise ValidationError(
                    message='{} not a valid value for {}'.format(val, k),
                    cursor_position=pos,
                )
            elif k == 'threads' and re.search(r'\d+', val) is None:
                pos = list(re.finditer(val, text))[0].end()
                raise ValidationError(
                    message='{} not a valid value for {}'.format(val, k),
                    cursor_position=pos,
                )
Ejemplo n.º 5
0
 def validate(self, document: Document) -> bool:
     text = document.text
     if text == '':
         raise ValidationError(message=("Must not be empty"))
     if '@' not in text:
         raise ValidationError(message=("Must contain a @"))
     return True
Ejemplo n.º 6
0
 def validate(self, document):
     # first, tokenize document.text
     tokens = self.console._get_tokens(document.text.strip())
     l = len(tokens)
     # then handle tokens
     commands = self.console.commands
     # when no token provided, do nothing
     if l == 0:
         return
     # when a command is being typed, mention if it is existing
     cmd = tokens[0]
     if l == 1 and cmd not in commands.keys():
         raise ValidationError(message="Unknown command")
     # when a valid first token is provided, handle command's validation, if
     #  any available
     elif l >= 1 and cmd in commands.keys():
         c = commands[cmd]._instance
         try:
             c._validate(*tokens[1:])
         except Exception as e:
             m = "Command syntax: %s{}" % c.signature.format(cmd)
             e = str(e)
             if not e.startswith("validate() "):
                 m = m.format([" (" + e + ")", ""][len(e) == 0])
             else:
                 m = m.format("")
             raise ValidationError(message=m)
     # otherwise, the command is considered bad
     else:
         raise ValidationError(message="Bad command")
Ejemplo n.º 7
0
 def validate(self, document: Document) -> None:
     if self.preselected_field_index is not None:
         field_selection, value = self.preselected_field_index, document.text
     else:
         field_selection, value = _configure_object_unpack_input(
             document.text)
     field = self.fields_by_index.get(field_selection, None)
     if field_selection.strip() == '0':
         return
     if field_selection.strip() == '':
         if any((isinstance(v, _MISSING_TYPE)
                 for v in self.result_values.values())):
             raise ValidationError(
                 message='Not all required field values have been set.')
         return
     if not field:
         raise ValidationError(message='Did not select a valid field')
     if field_selection and value is None:
         return
     _cast(value, field.type)  # Will raise error if fails datatype change
     field_validator = field.metadata.get('validator', None)
     if field_validator:
         try:
             is_invalid = field_validator(_cast(value,
                                                field.type)) is not True
         except Exception as e:
             raise ValidationError(message=e)
         if is_invalid:
             raise ValidationError(
                 message=field.metadata.get('validator_explanation'))
     field_picklist = field.metadata.get('picklist', None)
     if field_picklist and value not in field_picklist:
         raise ValidationError(
             message='Input does not match one of the allowed values')
     return super().validate(document)
Ejemplo n.º 8
0
    def validate(self, document):
        # Parse input document.
        # We use `match`, not `match_prefix`, because for validation, we want
        # the actual, unambiguous interpretation of the input.
        m = self.compiled_grammar.match(document.text)

        if m:
            for v in m.variables():
                validator = self.validators.get(v.varname)

                if validator:
                    # Unescape text.
                    unwrapped_text = self.compiled_grammar.unescape(
                        v.varname, v.value)

                    # Create a document, for the completions API (text/cursor_position)
                    inner_document = Document(unwrapped_text,
                                              len(unwrapped_text))

                    try:
                        validator.validate(inner_document)
                    except ValidationError as e:
                        raise ValidationError(index=v.start + e.index,
                                              message=e.message)
        else:
            raise ValidationError(index=len(document.text),
                                  message='Invalid command')
Ejemplo n.º 9
0
def to_x_subvalidator(text):
    """Checks if the todb statement is valid

    Parameters
    ----------
    text : str
        input statement

    """
    args = [arg for arg in text.split(None) if '=' not in arg]
    # Check number of args
    if len(args) > 2:
        raise ValidationError(
            message='Expected 2 argument, got {}'.format(len(args)),
            cursor_position=len(text),
        )
    # Checks if basepath dir exists
    dirpath = os.path.dirname(args[0])
    if not os.path.exists(dirpath):
        pos = list(re.finditer(dirpath, text))[0].end()
        raise ValidationError(
            message='Directory to basepath does not exist',
            cursor_position=pos,
        )
    # Checks if outpath exists
    dirpath = os.path.dirname(args[1])
    if not os.path.exists(dirpath):
        pos = list(re.finditer(dirpath, text))[0].end()
        raise ValidationError(
            message='Directory to save path does not exist',
            cursor_position=pos,
        )
Ejemplo n.º 10
0
Archivo: cli.py Proyecto: nuaays/argo
    def validate(self, document):
        if self.validator:
            if isinstance(self.validator, str) or isinstance(self.validator, unicode):
                try:
                    matched = re.match(self.validator, document.text)
                    if not matched:
                        raise ValidationError(message="{} does not match validator {}".format(document.text, self.validator),
                                              cursor_position=len(document.text))
                except Exception as e:
                    raise ValidationError(message="{} fails validation due to {}".format(document.text, e),
                                          cursor_position=len(document.text))

            elif callable(self.validator):
                try:
                    self.validator(document.text)
                except Exception as e:
                    raise ValidationError(message="{} fails validation due to {}".format(document.text, e))
            else:
                assert False, "Validator can be a regex string or a function"

        elif self.values:
            if document.text not in self.values:
                raise ValidationError(message="{} is not a valid input. Possible values are {}".format(document.text, self.values),
                                      cursor_position=len(document.text))
        else:
            pass
Ejemplo n.º 11
0
 def validate(self, document):
     if not document.text:
         raise ValidationError(message="Response Required",
                               cursor_position=0)
     if document.text not in info.get_valid_languages():
         raise ValidationError(message="Invalid language",
                               cursor_position=0)
Ejemplo n.º 12
0
def create_append_subvalidator(text):
    """Checks if the create or append statement is valid

    Parameters
    ----------
    text : str
        input statement

    """
    valid_keywords = ['intrahost_model', 'fitness_model', 'transmission_model']
    args = [arg for arg in text.split(None)[1:] if '=' not in arg]
    # Check number of arguments
    if len(args) > 2:
        raise ValidationError(
            message='Expected 2 arguments, got {}'.format(len(args)),
            cursor_position=len(text),
        )
    # Check keyword
    if args[0] not in valid_keywords:
        pos = list(re.finditer(args[0], text))[0].end()
        raise ValidationError(
            message='{} not a valid argument'.format(args[0]),
            cursor_position=pos,
        )
    # Check if model_name is a valid name
    if re.search(r'^[A-Za-z0-9\_\-\*]+$', args[1]) is None:
        raise ValidationError(
            message='{} not a a valid model name'.format(args[0]),
            cursor_position=len(text),
        )
Ejemplo n.º 13
0
    def validate(self, document):
        text = document.text
        i = 0
        if text and not text.isdigit():
            # Get index of fist non numeric character.
            # We want to move the cursor here.
            for i, c in enumerate(text):
                if not c.isdigit():
                    break

            raise ValidationError(
                message="This input contains non-numeric characters",
                cursor_position=i)
        v = int(text)
        if self.ranges[0] and v < self.ranges[0]:
            raise ValidationError(
                message="The number must be greater than %i" % self.ranges[0],
                cursor_position=0,
            )

        if self.ranges[1] and v > self.ranges[1]:
            raise ValidationError(
                message="The number must be smaller than %i" % self.ranges[1],
                cursor_position=0,
            )
Ejemplo n.º 14
0
 def validate(self, document):
     text = document.text
     if not text:
         raise ValidationError(message="Response Required",
                               cursor_position=0)
     if text.lower()[0] not in 'yn':
         raise ValidationError(message="Response must be [y]es or [n]o",
                               cursor_position=0)
Ejemplo n.º 15
0
 def validate(self, document):
     value = document.text
     if not value:
         raise ValidationError(message='Must be a numeric value')
     if not value.isdigit():
         raise ValidationError(message='Must be a numeric value')
     if int(value) < 1:
         raise ValidationError(message='Must be greater than 1')
Ejemplo n.º 16
0
def parse_dict(cmd):
    try:
        result = json.loads(cmd)
        if not isinstance(result, dict):
            raise ValidationError(message="value of %s is not a dict" % cmd)
        return result
    except:
        raise ValidationError(message="value of %s is not a dict" % cmd)
Ejemplo n.º 17
0
    def validate(self, document):
        if not exists(document.text):
            raise ValidationError(message='File doesn\'t exist!',
                                  cursor_position=len(document.text))

        if splitext(document.text)[1] != '.pem':
            raise ValidationError(message='File must be .pem extension!',
                                  cursor_position=len(document.text))
Ejemplo n.º 18
0
 def validate(self, document):
     if document.text == '':
         raise ValidationError(
             message='an existing file name is required')
     path = os.path.join(self.basedir, document.text)
     if os.path.exists(path):
         return True
     raise ValidationError(message=path + ' file does not exist')
Ejemplo n.º 19
0
 def validate(self, document: Document) -> bool:
     text = document.text.replace(" ", "")
     if text == "65A1B5FF195B56353CC63DFFCC40EF1228271441":
         raise ValidationError(message="This is the TEST journalist fingerprint")
     if text == "600BC6D5142C68F35DDBCEA87B597104EDDDC102":
         raise ValidationError(message="This is the TEST admin fingerprint")
     if not re.match("[a-fA-F0-9]{40}$", text):
         raise ValidationError(message="fingerprints must be 40 hexadecimal characters")
     return True
Ejemplo n.º 20
0
 def validate(self, document):
     ok = regex.match('^[0-9]*$', document.text)
     if not ok:
         raise ValidationError(message='Please enter only numeric value',
                               cursor_position=len(document.text))
     if int(document.text) < 1 or int(document.text) > 10:
         raise ValidationError(
             message='Please enter a number between 1 and 10',
             cursor_position=len(document.text))
Ejemplo n.º 21
0
 def validate(self, document):
     text = document.text
     if not text:
         raise ValidationError(message="Respose Required",
                               cursor_position=0)
     if text.lower()[0] not in 'cea':
         raise ValidationError(
             message="Response must be [c]ommit, [e]dit, or [a]bort",
             cursor_position=0)
Ejemplo n.º 22
0
 def validate(self, document):
     try:
         if document.text != '': int(document.text)
     except:
         raise ValidationError(message='Invalid port number',
                               cursor_position=len(document.text))
     if document.text != '' and int(document.text) > 65536:
         raise ValidationError(message='Port number cannot exceed 65536',
                               cursor_position=len(document.text))
Ejemplo n.º 23
0
    def validate(self, document):
        current = string_to_boolean(document.text)

        if current is None:
            raise ValidationError(message='Please answer Yes or No.')

        if callable(
                self.function) and not self.function(self.answers, current):
            raise ValidationError(message='Invalid input.')
Ejemplo n.º 24
0
 def validate(self, document):
     text = document.text
     if text not in self.allowed_values:
         if self.show_possible:
             raise ValidationError(message='This input is not allowed, '
                                   ' please choose from %s' %
                                   self.allowed_values)
         else:
             raise ValidationError(message='This input is not allowed')
Ejemplo n.º 25
0
    def validate(self, document) -> None:
        text = document.text

        if not text.isdecimal():
            raise ValidationError(message="Must be a number",
                                  cursor_position=len(text))

        if int(text) != self.solution:
            raise ValidationError(message="Wrong port number",
                                  cursor_position=len(text))
Ejemplo n.º 26
0
 def validate(self, document):
     try:
         if int(document.text) not in range(1, len(get_device_list()) + 1):
             raise ValidationError(
                 message='tips: 输入的设备序号不正确,请重新输入!',
                 cursor_position=len(
                     document.text))  # Move cursor to end of input.
     except:
         raise ValidationError(message='tips: 输入的设备序号不正确,请重新输入!',
                               cursor_position=len(document.text))
Ejemplo n.º 27
0
    def validate(self, document):
        try:
            port = int(document.text)
        except ValueError:
            raise ValidationError(message='Must be a number type!',
                                  cursor_position=len(document.text))

        if not 1 <= port <= 65535:
            raise ValidationError(message='Port is invalid!',
                                  cursor_position=len(document.text))
Ejemplo n.º 28
0
    def validate(self, document):
        text = document.text

        if not text or (text and not text.isdigit()):
            raise ValidationError(
                message='This input contains non-numeric characters')
        elif (int(text) % self.size) != 0:
            raise ValidationError(
                message='This plant needs to have a multiple of {} squares'.
                format(self.size))
Ejemplo n.º 29
0
 def validate(self, document):
     text = document.text.lower()
     # Raise error if admin tries to disable v3 when v2
     # is already disabled.
     if text == 'no' and \
             not self.caller._config_in_progress.get("v2_onion_services"):  # noqa: E501
         raise ValidationError(message="Since you disabled v2 onion services, you must enable v3 onion services.")  # noqa: E501
     if text == 'yes' or text == 'no':
         return True
     raise ValidationError(message="Must be either yes or no")
Ejemplo n.º 30
0
    async def validate_async(self, document: Document) -> None:
        (_, hostname, path, _, _, _) = urllib.parse.urlparse(url=document.text)

        if 'leetcode' not in hostname.lower():
            raise ValidationError(
                message='Please enter a URL points to LeetCode site.')

        if (match := re.search(r'/problems/([^/]+)/?', path)) is None:
            raise ValidationError(
                message='Please enter a valid URL of LeetCode problem')