Example #1
0
 def test_recursive(self):
     f = FilePathField(path=self.path, recursive=True, match=r'^.*?\.py$')
     f.choices.sort()
     expected = [
         ('/filepathfield_test_dir/__init__.py', '__init__.py'),
         ('/filepathfield_test_dir/a.py', 'a.py'),
         ('/filepathfield_test_dir/ab.py', 'ab.py'),
         ('/filepathfield_test_dir/b.py', 'b.py'),
         ('/filepathfield_test_dir/c/__init__.py', 'c/__init__.py'),
         ('/filepathfield_test_dir/c/d.py', 'c/d.py'),
         ('/filepathfield_test_dir/c/e.py', 'c/e.py'),
         ('/filepathfield_test_dir/c/f/__init__.py', 'c/f/__init__.py'),
         ('/filepathfield_test_dir/c/f/g.py', 'c/f/g.py'),
     ]
     self.assertChoices(f, expected)
Example #2
0
 def test_recursive(self):
     f = FilePathField(path=self.path, recursive=True, match=r"^.*?\.py$")
     expected = [
         ("/filepathfield_test_dir/__init__.py", "__init__.py"),
         ("/filepathfield_test_dir/a.py", "a.py"),
         ("/filepathfield_test_dir/ab.py", "ab.py"),
         ("/filepathfield_test_dir/b.py", "b.py"),
         ("/filepathfield_test_dir/c/__init__.py", "c/__init__.py"),
         ("/filepathfield_test_dir/c/d.py", "c/d.py"),
         ("/filepathfield_test_dir/c/e.py", "c/e.py"),
         ("/filepathfield_test_dir/c/f/__init__.py", "c/f/__init__.py"),
         ("/filepathfield_test_dir/c/f/g.py", "c/f/g.py"),
         ("/filepathfield_test_dir/h/__init__.py", "h/__init__.py"),
         ("/filepathfield_test_dir/j/__init__.py", "j/__init__.py"),
     ]
     self.assertChoices(f, expected)
Example #3
0
 def test_filepathfield_3(self):
     path = upath(forms.__file__)
     path = os.path.dirname(os.path.abspath(path)) + '/'
     f = FilePathField(path=path, match='^.*?\.py$')
     f.choices.sort()
     expected = [('/django/forms/__init__.py', '__init__.py'),
                 ('/django/forms/boundfield.py', 'boundfield.py'),
                 ('/django/forms/fields.py', 'fields.py'),
                 ('/django/forms/forms.py', 'forms.py'),
                 ('/django/forms/formsets.py', 'formsets.py'),
                 ('/django/forms/models.py', 'models.py'),
                 ('/django/forms/utils.py', 'utils.py'),
                 ('/django/forms/widgets.py', 'widgets.py')]
     for exp, got in zip(expected, fix_os_paths(f.choices)):
         self.assertEqual(exp[1], got[1])
         self.assertTrue(got[0].endswith(exp[0]))
Example #4
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.initial['cache_size'] = 0

        self.fields['maxConnections'] = IntegerField(
            label='Max connections:',
            required=False,
            initial=64000,
            min_value=1,
            widget=NumberInput(attrs={"class": "form-control"}))

        self.fields['yaraScanType'] = ChoiceField(
            label='Yara scan type:',
            required=False,
            initial="packet",
            choices=[("packet", "Packet"), ("stream", "Stream")],
            widget=Select(attrs={"class": "form-control"}))

        self.fields['yaraScanMaxSize'] = IntegerField(
            label='Yara scan max size:',
            required=False,
            initial=16384,
            min_value=1,
            widget=NumberInput(attrs={"class": "form-control"}))

        self.fields['maxMemoryUsage'] = IntegerField(
            label='Max memory usage:',
            required=False,
            initial=200,
            min_value=1,
            widget=NumberInput(attrs={"class": "form-control"}))

        self.fields['yaraRuleFile'] = FilePathField(
            label='Yara rule file:',
            path="{}f{}/".format(CONF_PATH, "content_inspection"),
            required=True,
            widget=Select(attrs={'class': 'form-control select2'}),
            match=".*\.yar$")

        self.fields["mmdarwin_enabled"].disabled = True
        if not self.fields["yaraRuleFile"].widget.choices:
            self.fields["yaraRuleFile"].disabled = True
Example #5
0
class AllFieldTypesForm(Form):
    char = CharField()
    int_ = IntegerField()
    date = DateField()
    time = TimeField()
    datetime_ = DateTimeField()
    regex = RegexField(regex='^[a-f]{3}$')
    email = EmailField()
    file = FileField()
    # image = ImageField()
    url = URLField()
    bool = BooleanField()
    nullbool = NullBooleanField()
    choice = ChoiceField(choices=(('test choice', 'yay test choice'), ))
    multichoice = MultipleChoiceField(choices=(
        ('test choice', 'yay test choice'),
        ('test choice 2', 'yay another choice'),
        ('test choice 3', 'yay test choice'),
    ))
    float = FloatField()
    decimal = DecimalField()
    ip = IPAddressField()
    generic_ip = GenericIPAddressField()
    filepath = FilePathField(path=tempfile.gettempdir(),
                             allow_files=True,
                             allow_folders=True)
    slug = SlugField()
    typed_choice = TypedChoiceField(choices=(
        (1, 'test'),
        (2, 'test 2'),
        (3, 'bah'),
    ),
                                    coerce=int)
    typed_multichoice = TypedMultipleChoiceField(choices=(
        (1, 'test'),
        (2, 'test 2'),
        (3, 'bah'),
    ),
                                                 coerce=int)
    model_choice = ModelChoiceField(queryset=get_user_model().objects.all())
    model_multichoice = ModelMultipleChoiceField(
        queryset=get_user_model().objects.all())
Example #6
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['database'] = FilePathField(
            path="{}f{}/".format(CONF_PATH, "hostlookup"),
            required=False,
            widget=Select(attrs={'class': 'form-control select2'}),
            match=".*\.db$")

        try:
            if not os.path.exists(self.initial['database']):
                del self.initial['database']

            if self.initial.get('database', None) is None:
                self.initial['enabled'] = False

        except KeyError:
            pass

        # <= 1, because there is the "empty" choice to consider
        if not self['database'].field.choices or len(
                self['database'].field.choices) <= 1:
            self.fields['enabled'].disabled = True
Example #7
0
 def test_filepathfield_2(self):
     path = os.path.dirname(os.path.abspath(forms.__file__)) + '/'
     f = FilePathField(path=path)
     f.choices = [p for p in f.choices if p[0].endswith('.py')]
     f.choices.sort()
     expected = [
         ('/django/forms/__init__.py', '__init__.py'),
         ('/django/forms/boundfield.py', 'boundfield.py'),
         ('/django/forms/fields.py', 'fields.py'),
         ('/django/forms/forms.py', 'forms.py'),
         ('/django/forms/formsets.py', 'formsets.py'),
         ('/django/forms/models.py', 'models.py'),
         ('/django/forms/renderers.py', 'renderers.py'),
         ('/django/forms/utils.py', 'utils.py'),
         ('/django/forms/widgets.py', 'widgets.py')
     ]
     for exp, got in zip(expected, fix_os_paths(f.choices)):
         self.assertEqual(exp[1], got[1])
         self.assertTrue(got[0].endswith(exp[0]))
     msg = "'Select a valid choice. fields.py is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('fields.py')
     self.assertTrue(fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py'))
Example #8
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # not shown in GUI
        self.fields['token_map_path'] = CharField(
            required=False,
            initial="/home/darwin/conf/fdga/fdga_tokens.csv",
            widget=HiddenInput())

        # not shown in GUI
        self.fields['max_tokens'] = IntegerField(required=False,
                                                 initial=75,
                                                 min_value=1,
                                                 widget=HiddenInput())

        self.fields['model_path'] = FilePathField(
            label="Model:",
            path="{}f{}/".format(CONF_PATH, "dga"),
            required=False,
            widget=Select(attrs={'class': 'form-control select2'}),
            match=".*\.pb$")

        try:
            if not os.path.exists(self.initial['model_path']):
                del self.initial['model_path']

            if self.initial.get('model_path', None) is None:
                self.initial['enabled'] = False

        except KeyError:
            pass

        # <= 1, because there is the "empty" choice to consider
        if not self['model_path'].field.choices or len(
                self['model_path'].field.choices) <= 1:
            self.fields['enabled'].disabled = True
Example #9
0
 def test_recursive_no_folders_or_files(self):
     f = FilePathField(path=self.path,
                       recursive=True,
                       allow_folders=False,
                       allow_files=False)
     self.assertChoices(f, [])
Example #10
0
 def test_match(self):
     f = FilePathField(path=self.path, match=r"^.*?\.py$")
     self.assertChoices(f, self.expected_choices[:4])
Example #11
0
 def test_no_options(self):
     f = FilePathField(path=self.path)
     expected = [
         ("/filepathfield_test_dir/README", "README"),
     ] + self.expected_choices[:4]
     self.assertChoices(f, expected)
Example #12
0
 def test_nonexistent_path(self):
     with self.assertRaisesMessage(FileNotFoundError, "nonexistent"):
         FilePathField(path="nonexistent")
Example #13
0
 def __init__(self, dest, path, *args, **kwargs):
     field = FilePathField(path=path)
     super(FilePathFilter, self).__init__(dest,
                                          field=field,
                                          *args,
                                          **kwargs)
Example #14
0
 def test_clean(self):
     f = FilePathField(path=self.path)
     msg = "'Select a valid choice. a.py is not one of the available choices.'"
     with self.assertRaisesMessage(ValidationError, msg):
         f.clean('a.py')
     self.assertEqual(fix_os_paths(f.clean(self.path + 'a.py')), '/filepathfield_test_dir/a.py')
Example #15
0
class RegisterMusicForm(Form):
    name = forms.CharField()
    directory = FilePathField(path='/', required=False,
                              widget=forms.ClearableFileInput(attrs=
                                                               {'multiple': True}),
                              )