Esempio n. 1
0
    def test_upload_with_invalid_username_should_fail(self, mock_logger,
                                                      username, message_key):
        filename = "map_1500.dat"
        existing_filename = "existing_unlocked.dat"

        self.copy_test_data_file(existing_filename, self.uploads_dir, filename)
        existing_file_content = self.load_test_data_file(existing_filename)

        upload_file_content = self.load_test_data_file(filename)

        data = OrderedMultiDict()
        data.add("userName", username)
        data.add("map", (BytesIO(upload_file_content), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        # Verify that the existing map file was NOT overwritten
        self.verify_file_content(self.uploads_dir, filename,
                                 existing_file_content)

        self.verify_flash_message_by_key(message_key, response.data)

        if username:
            mock_logger.warn.assert_called_with(
                self.get_log_message(message_key), username)
        else:
            mock_logger.warn.assert_called_with(
                self.get_log_message(message_key))
Esempio n. 2
0
    def test_upload_with_invalid_filename_and_file_already_exists_should_fail(
            self, mock_logger, filename):
        username = "******"
        message_key = "MAP_UPLOAD_FILENAME_INVALID"

        self.copy_test_data_file(filename, self.uploads_dir)
        existing_file_content = self.load_test_data_file(filename)

        # Upload a valid map file, but rename it to the existing filename
        upload_file_content = self.load_test_data_file("map_1500.dat")

        data = OrderedMultiDict()
        data.add("userName", username)
        data.add("map", (BytesIO(upload_file_content), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        # Verify that the existing map file was NOT overwritten
        self.verify_file_content(self.uploads_dir, filename,
                                 existing_file_content)

        self.verify_flash_message_by_key(message_key, response.data, filename)
        mock_logger.warn.assert_called_with(self.get_log_message(message_key),
                                            filename, username)
Esempio n. 3
0
def test_multidict_encoding():
    d = OrderedMultiDict()
    d.add("2013-10-10T23:26:05.657975+0000", "2013-10-10T23:26:05.657975+0000")
    assert (
        urls.url_encode(d)
        == "2013-10-10T23%3A26%3A05.657975%2B0000=2013-10-10T23%3A26%3A05.657975%2B0000"
    )
Esempio n. 4
0
    def test_upload_where_existing_file_is_already_locked_should_fail(
            self, mock_logger):
        username = "******"
        filename = "map_1500.dat"
        existing_filename = "existing_locked.dat"
        message_key = "MAP_UPLOAD_EXISTING_MAP_LOCKED"

        self.copy_test_data_file(existing_filename, self.uploads_dir, filename)
        existing_file_content = self.load_test_data_file(existing_filename)

        upload_file_content = self.load_test_data_file(filename)

        data = OrderedMultiDict()
        data.add("userName", username)
        data.add("map", (BytesIO(upload_file_content), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        # Verify that the existing map file was NOT overwritten
        self.verify_file_content(self.uploads_dir, filename,
                                 existing_file_content)

        self.verify_flash_message_by_key(message_key, response.data, filename)
        mock_logger.warn.assert_called_with(self.get_log_message(message_key),
                                            filename, username)
Esempio n. 5
0
    def test_upload_single_file_should_be_successful(self, mock_logger):
        username = "******"
        filename = "map_1500.dat"
        message_key = "MAP_UPLOAD_SUCCESS"

        self.copy_test_data_file("existing_unlocked.dat", self.uploads_dir,
                                 filename)

        original_file_content = self.load_test_data_file(filename)

        data = OrderedMultiDict()
        data.add("userName", username)
        data.add("map", (BytesIO(original_file_content), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        # Verify that the new map file was uploaded and locked
        expected_nbt_file = self.load_test_data_nbt_file(filename)
        uploaded_nbt_file = self.load_uploaded_nbt_file(filename)
        self.verify_matching_nbt_values(expected_nbt_file, uploaded_nbt_file)

        assert get_nbt_map_value(uploaded_nbt_file, "locked") == 1

        self.verify_flash_message_by_key(message_key, response.data, filename)
        mock_logger.info.assert_called_with(self.get_log_message(message_key),
                                            filename, username)
Esempio n. 6
0
def test_multidict_encoding():
    d = OrderedMultiDict()
    d.add("2013-10-10T23:26:05.657975+0000", "2013-10-10T23:26:05.657975+0000")
    assert (
        urls.url_encode(d)
        == "2013-10-10T23%3A26%3A05.657975%2B0000=2013-10-10T23%3A26%3A05.657975%2B0000"
    )
Esempio n. 7
0
class Form(object):
    """Representation of an HTML form."""
    def __init__(self, parsed):
        parsed = helpers.ensure_soup(parsed)
        if parsed.name != 'form':
            parsed = parsed.find('form')
        self.parsed = parsed
        self.action = self.parsed.get('action')
        self.method = self.parsed.get('method', 'get')
        self.fields = OrderedMultiDict()
        for field in _parse_fields(self.parsed):
            self.add_field(field)

    def add_field(self, field):
        """Add a field.

        :param field: Field to add
        :raise: ValueError if `field` is not an instance of `BaseField`.

        """
        if not isinstance(field, fields.BaseField):
            raise ValueError('Argument "field" must be an instance of '
                             'BaseField')
        self.fields.add(field.name, field)

    @property
    def submit_fields(self):
        return _filter_fields(self.fields,
                              lambda field: isinstance(field, fields.Submit))

    @encode_if_py2
    def __repr__(self):
        state = u', '.join([
            u'{0}={1}'.format(name, field.value)
            for name, field in self.fields.items(multi=True)
        ])
        if state:
            return u'<RoboForm {0}>'.format(state)
        return u'<RoboForm>'

    def keys(self):
        return self.fields.keys()

    def __getitem__(self, item):
        return self.fields[item]

    def __setitem__(self, key, value):
        self.fields[key].value = value

    def serialize(self, submit=None):
        """Serialize each form field to a Payload container.

        :param Submit submit: Optional `Submit` to click, if form includes
            multiple submits
        :return: Payload instance

        """
        include_fields = prepare_fields(self.fields, self.submit_fields,
                                        submit)
        return Payload.from_fields(include_fields)
Esempio n. 8
0
    def test_upload_file_that_already_exists_should_fail(self, mock_logger):
        username = "******"
        filename = "mrt_v5_final_elevated_centre_station.schematic"
        uploaded_filename = self.uploaded_filename(username, filename)
        impostor_filename = "mrt_v5_final_underground_single_track.schematic"
        message_key = "SCHEMATIC_UPLOAD_FILE_EXISTS"

        # Copy an impostor file with different content to the uploads directory with the same name as the file to upload
        self.copy_test_data_file(impostor_filename, self.uploads_dir,
                                 uploaded_filename)

        original_file_content = self.load_test_data_file(filename)

        data = OrderedMultiDict()
        data.add("userName", username)
        data.add("schematic", (BytesIO(original_file_content), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        # Verify that the uploads directory has only the impostor file, and the file has not been modified
        files = os.listdir(self.uploads_dir)
        assert len(files) == 1

        impostor_file_content = self.load_test_data_file(impostor_filename)
        self.verify_file_content(self.uploads_dir, uploaded_filename,
                                 impostor_file_content)

        self.verify_flash_message_by_key(message_key, response.data,
                                         uploaded_filename)
        mock_logger.warn.assert_called_with(self.get_log_message(message_key),
                                            uploaded_filename, username)
Esempio n. 9
0
 def test_multidict_encoding(self):
     d = OrderedMultiDict()
     d.add('2013-10-10T23:26:05.657975+0000',
           '2013-10-10T23:26:05.657975+0000')
     self.assert_equal(
         urls.url_encode(d),
         '2013-10-10T23%3A26%3A05.657975%2B0000=2013-10-10T23%3A26%3A05.657975%2B0000'
     )
  def create_request_data(self, filename):
    pair = os.path.splitext(filename)

    data = OrderedMultiDict()
    data.add("fileRoot", pair[0])
    data.add("fileExtension", pair[1][1:])

    return data
Esempio n. 11
0
File: xor.py Progetto: Mattias-/xor
 def __get_query_args(req):
     d = OrderedMultiDict()
     if len(req.query_string) > 0:
         arg_list = req.query_string.split('&')
         arg_list = map(unquote, arg_list)
         for arg in arg_list:
             spl = arg.split('=', 1)
             spl.append(None)
             d.add(spl[0], spl[1])
     return d
Esempio n. 12
0
    def test_parse_arg_keys(self):
        arg_dict = OrderedMultiDict()
        arg_dict.add('f', 'val')
        arg_dict.add('b', 'val')
        arg_dict.add('x', 'val')

        reference_result = tuple(['f', 'b', 'x'])

        test_result = strict.KeywordParser.\
            _parse_arg_keys(arg_dict)

        self.assertEqual(test_result, reference_result)
Esempio n. 13
0
File: xor.py Progetto: Mattias-/xor
 def __get_post_args(req):
     d = OrderedMultiDict()
     if req.method == 'POST':
         content = req.environ['wsgi.input']
         post_data = content.read(req.content_length)
         arg_list = post_data.split('&')
         arg_list = map(unquote, arg_list)
         for arg in arg_list:
             spl = arg.split('=', 1)
             spl.append(None)
             d.add(spl[0], spl[1])
     return d
Esempio n. 14
0
    def test_upload_with_no_files_should_fail(self, mock_logger):
        username = "******"
        message_key = "MAP_UPLOAD_NO_FILES"

        data = OrderedMultiDict()
        data.add("userName", username)

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        self.verify_flash_message_by_key(message_key, response.data)
        mock_logger.warn.assert_called_with(self.get_log_message(message_key),
                                            username)
Esempio n. 15
0
    def test_upload_multiple_files_should_be_successful(self, mock_logger):
        username = "******"
        message_key = "MAP_UPLOAD_SUCCESS"

        # Upload 7 files
        filenames = [
            "map_1500.dat", "map_2000.dat", "map_1501.dat", "map_1502.dat",
            "map_1001.dat", "map_1503.dat", "map_1504.dat"
        ]

        for filename in filenames:
            self.copy_test_data_file("existing_unlocked.dat", self.uploads_dir,
                                     filename)

        original_files = self.load_test_data_files(filenames)

        data = OrderedMultiDict()
        data.add("userName", username)

        for filename in original_files:
            data.add("map", (BytesIO(original_files[filename]), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        logger_calls = []

        for filename in original_files:
            # Verify that the new map files were uploaded and locked
            expected_nbt_file = self.load_test_data_nbt_file(filename)
            uploaded_nbt_file = self.load_uploaded_nbt_file(filename)
            self.verify_matching_nbt_values(expected_nbt_file,
                                            uploaded_nbt_file)

            assert get_nbt_map_value(uploaded_nbt_file, "locked") == 1

            self.verify_flash_message_by_key(message_key, response.data,
                                             filename)
            logger_calls.append(
                call(self.get_log_message(message_key), filename, username))

        mock_logger.info.assert_has_calls(logger_calls, any_order=True)
Esempio n. 16
0
    def test_upload_multiple_files_should_be_successful(self, mock_logger):
        username = "******"
        message_key = "SCHEMATIC_UPLOAD_SUCCESS"

        # Upload 5 files
        filenames = [
            "mrt_v5_final_elevated_centre_station.schem",
            "mrt_v5_final_elevated_side_station.schematic",
            "mrt_v5_final_elevated_single_track.schematic",
            "mrt_v5_final_elevated_double_track.schematic",
            "mrt_v5_final_elevated_double_curve.schematic"
        ]

        original_files = self.load_test_data_files(filenames)

        data = OrderedMultiDict()
        data.add("userName", username)

        for filename in original_files:
            data.add("schematic",
                     (BytesIO(original_files[filename]), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        logger_calls = []

        for filename in original_files:
            uploaded_filename = self.uploaded_filename(username, filename)

            self.verify_file_content(self.uploads_dir, uploaded_filename,
                                     original_files[filename])

            self.verify_flash_message_by_key(message_key, response.data,
                                             uploaded_filename)
            logger_calls.append(
                call(self.get_log_message(message_key), uploaded_filename,
                     username))

        mock_logger.info.assert_has_calls(logger_calls, any_order=True)
Esempio n. 17
0
    def test_upload_with_invalid_file_should_fail(self, mock_logger, filename,
                                                  message_key):
        username = "******"
        uploaded_filename = self.uploaded_filename(username, filename)
        original_file_content = self.load_test_data_file(filename)

        data = OrderedMultiDict()
        data.add("userName", username)
        data.add("schematic", (BytesIO(original_file_content), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        self.verify_schematic_uploads_dir_is_empty()

        self.verify_flash_message_by_key(message_key, response.data,
                                         uploaded_filename)
        mock_logger.warn.assert_called_with(self.get_log_message(message_key),
                                            uploaded_filename, username)
Esempio n. 18
0
    def test_upload_with_too_many_files_should_fail(self, mock_logger):
        username = "******"
        message_key = "SCHEMATIC_UPLOAD_TOO_MANY_FILES"

        # Upload 12 files, over the limit of 10.
        filenames = [
            "mrt_v5_final_elevated_centre_station.schematic",
            "mrt_v5_final_elevated_side_station.schematic",
            "mrt_v5_final_elevated_single_track.schematic",
            "mrt_v5_final_elevated_double_track.schematic",
            "mrt_v5_final_elevated_double_curve.schematic",
            "mrt_v5_final_ground_centre_station.schematic",
            "mrt_v5_final_ground_side_station.schematic",
            "mrt_v5_final_ground_single_track.schematic",
            "mrt_v5_final_ground_double_track.schematic",
            "mrt_v5_final_ground_double_curve.schematic",
            "mrt_v5_final_subground_centre_station.schematic",
            "mrt_v5_final_subground_side_station.schematic"
        ]

        original_files = self.load_test_data_files(filenames)

        data = OrderedMultiDict()
        data.add("userName", username)

        for filename in original_files:
            data.add("schematic",
                     (BytesIO(original_files[filename]), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        self.verify_schematic_uploads_dir_is_empty()

        self.verify_flash_message_by_key(message_key, response.data)
        mock_logger.warn.assert_called_with(self.get_log_message(message_key),
                                            username)
Esempio n. 19
0
    def test_upload_with_too_many_files_should_fail(self, mock_logger):
        username = "******"
        existing_filename = "existing_unlocked.dat"
        message_key = "MAP_UPLOAD_TOO_MANY_FILES"

        # Upload 11 files, over the limit of 10.
        filenames = [
            "map_1001.dat", "map_1500.dat", "map_1501.dat", "map_1502.dat",
            "map_1503.dat", "map_1504.dat", "map_1505.dat", "map_1506.dat",
            "map_1507.dat", "map_1508.dat", "map_2000.dat"
        ]

        for filename in filenames:
            self.copy_test_data_file(existing_filename, self.uploads_dir,
                                     filename)

        existing_file_content = self.load_test_data_file(existing_filename)

        upload_files = self.load_test_data_files(filenames)

        data = OrderedMultiDict()
        data.add("userName", username)

        for filename in upload_files:
            data.add("map", (BytesIO(upload_files[filename]), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        # Verify that none of the existing map files were overwritten
        for filename in filenames:
            self.verify_file_content(self.uploads_dir, filename,
                                     existing_file_content)

        self.verify_flash_message_by_key(message_key, response.data)
        mock_logger.warn.assert_called_with(self.get_log_message(message_key),
                                            username)
Esempio n. 20
0
 def test_ordered_multidict_encoding(self):
     d = OrderedMultiDict()
     d.add("foo", 1)
     d.add("foo", 2)
     d.add("foo", 3)
     d.add("bar", 0)
     d.add("foo", 4)
     assert urls.url_encode(d) == "foo=1&foo=2&foo=3&bar=0&foo=4"
Esempio n. 21
0
def test_ordered_multidict_encoding():
    d = OrderedMultiDict()
    d.add('foo', 1)
    d.add('foo', 2)
    d.add('foo', 3)
    d.add('bar', 0)
    d.add('foo', 4)
    assert urls.url_encode(d) == 'foo=1&foo=2&foo=3&bar=0&foo=4'
Esempio n. 22
0
def test_ordered_multidict_encoding():
    d = OrderedMultiDict()
    d.add('foo', 1)
    d.add('foo', 2)
    d.add('foo', 3)
    d.add('bar', 0)
    d.add('foo', 4)
    assert urls.url_encode(d) == 'foo=1&foo=2&foo=3&bar=0&foo=4'
Esempio n. 23
0
def test_ordered_multidict_encoding():
    d = OrderedMultiDict()
    d.add("foo", 1)
    d.add("foo", 2)
    d.add("foo", 3)
    d.add("bar", 0)
    d.add("foo", 4)
    assert urls.url_encode(d) == "foo=1&foo=2&foo=3&bar=0&foo=4"
Esempio n. 24
0
 def test_ordered_multidict_encoding(self):
     d = OrderedMultiDict()
     d.add('foo', 1)
     d.add('foo', 2)
     d.add('foo', 3)
     d.add('bar', 0)
     d.add('foo', 4)
     self.assert_equal(urls.url_encode(d), 'foo=1&foo=2&foo=3&bar=0&foo=4')
Esempio n. 25
0
def test_multidict_pickle():
    """MultiDict types are pickle-able"""
    for protocol in xrange(pickle.HIGHEST_PROTOCOL + 1):
        print 'pickling protocol', protocol
        d = MultiDict()
        d.setlist('foo', [1, 2, 3, 4])
        d.setlist('bar', 'foo bar baz'.split())
        s = pickle.dumps(d, protocol)
        ud = pickle.loads(s)
        assert type(ud) is type(d)
        assert ud == d
        assert pickle.loads(s.replace('werkzeug.datastructures',
                                      'werkzeug')) == d
        ud['newkey'] = 'bla'
        assert ud != d

        d2 = OrderedMultiDict(d)
        d2.add('foo', 5)
        s = pickle.dumps(d2, protocol)
        ud = pickle.loads(s)
        assert type(ud) is type(d2)
        assert ud == d2
        ud['newkey'] = 'bla'
        print ud
        print d2
        assert ud != d2

        im = ImmutableMultiDict(d)
        assert im == d
        s = pickle.dumps(im, protocol)
        ud = pickle.loads(s)
        assert ud == im
        assert type(ud) is type(im)

        c = CombinedMultiDict([ud, im])
        cc = pickle.loads(pickle.dumps(c, protocol))
        assert c == cc
        assert type(c) is type(cc)
Esempio n. 26
0
    def test_upload_single_file_should_be_successful(self, mock_logger,
                                                     filename):
        username = "******"
        uploaded_filename = self.uploaded_filename(username, filename)
        original_file_content = self.load_test_data_file(filename)
        message_key = "SCHEMATIC_UPLOAD_SUCCESS"

        data = OrderedMultiDict()
        data.add("userName", username)
        data.add("schematic", (BytesIO(original_file_content), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        self.verify_file_content(self.uploads_dir, uploaded_filename,
                                 original_file_content)

        self.verify_flash_message_by_key(message_key, response.data,
                                         uploaded_filename)
        mock_logger.info.assert_called_with(self.get_log_message(message_key),
                                            uploaded_filename, username)
Esempio n. 27
0
    def test_upload_with_invalid_filename_should_fail(self, mock_logger,
                                                      filename):
        username = "******"
        message_key = "MAP_UPLOAD_FILENAME_INVALID"

        upload_file_content = self.load_test_data_file(filename)

        data = OrderedMultiDict()
        data.add("userName", username)
        data.add("map", (BytesIO(upload_file_content), filename))

        response = self.perform_upload(data)

        assert response.status_code == 200
        assert response.mimetype == "text/html"

        # Verify that the new map file was NOT uploaded
        uploaded_file_path = os.path.join(self.uploads_dir, filename)
        assert os.path.isfile(uploaded_file_path) == False

        self.verify_flash_message_by_key(message_key, response.data, filename)
        mock_logger.warn.assert_called_with(self.get_log_message(message_key),
                                            filename, username)
Esempio n. 28
0
def test_multidict_pickle():
    """MultiDict types are pickle-able"""
    for protocol in xrange(pickle.HIGHEST_PROTOCOL + 1):
        print "pickling protocol", protocol
        d = MultiDict()
        d.setlist("foo", [1, 2, 3, 4])
        d.setlist("bar", "foo bar baz".split())
        s = pickle.dumps(d, protocol)
        ud = pickle.loads(s)
        assert type(ud) is type(d)
        assert ud == d
        assert pickle.loads(s.replace("werkzeug.datastructures", "werkzeug")) == d
        ud["newkey"] = "bla"
        assert ud != d

        d2 = OrderedMultiDict(d)
        d2.add("foo", 5)
        s = pickle.dumps(d2, protocol)
        ud = pickle.loads(s)
        assert type(ud) is type(d2)
        assert ud == d2
        ud["newkey"] = "bla"
        print ud
        print d2
        assert ud != d2

        im = ImmutableMultiDict(d)
        assert im == d
        s = pickle.dumps(im, protocol)
        ud = pickle.loads(s)
        assert ud == im
        assert type(ud) is type(im)

        c = CombinedMultiDict([ud, im])
        cc = pickle.loads(pickle.dumps(c, protocol))
        assert c == cc
        assert type(c) is type(cc)
Esempio n. 29
0
def test_multidict_pickle():
    """MultiDict types are pickle-able"""
    for protocol in xrange(pickle.HIGHEST_PROTOCOL + 1):
        print 'pickling protocol', protocol
        d = MultiDict()
        d.setlist('foo', [1, 2, 3, 4])
        d.setlist('bar', 'foo bar baz'.split())
        s = pickle.dumps(d, protocol)
        ud = pickle.loads(s)
        assert type(ud) is type(d)
        assert ud == d
        assert pickle.loads(s.replace('werkzeug.datastructures', 'werkzeug')) == d
        ud['newkey'] = 'bla'
        assert ud != d

        d2 = OrderedMultiDict(d)
        d2.add('foo', 5)
        s = pickle.dumps(d2, protocol)
        ud = pickle.loads(s)
        assert type(ud) is type(d2)
        assert ud == d2
        ud['newkey'] = 'bla'
        print ud
        print d2
        assert ud != d2

        im = ImmutableMultiDict(d)
        assert im == d
        s = pickle.dumps(im, protocol)
        ud = pickle.loads(s)
        assert ud == im
        assert type(ud) is type(im)

        c = CombinedMultiDict([ud, im])
        cc = pickle.loads(pickle.dumps(c, protocol))
        assert c == cc
        assert type(c) is type(cc)
Esempio n. 30
0
def test_ordered_multidict_encoding():
    """"Make sure URLs are properly encoded from OrderedMultiDicts"""
    d = OrderedMultiDict()
    d.add('foo', 1)
    d.add('foo', 2)
    d.add('foo', 3)
    d.add('bar', 0)
    d.add('foo', 4)
    assert url_encode(d) == 'foo=1&foo=2&foo=3&bar=0&foo=4'
Esempio n. 31
0
def test_ordered_multidict_encoding():
    """"Make sure URLs are properly encoded from OrderedMultiDicts"""
    d = OrderedMultiDict()
    d.add('foo', 1)
    d.add('foo', 2)
    d.add('foo', 3)
    d.add('bar', 0)
    d.add('foo', 4)
    assert url_encode(d) == 'foo=1&foo=2&foo=3&bar=0&foo=4'
Esempio n. 32
0
    def test_upload_same_file_twice_should_fail(self, mock_logger):
        username = "******"
        filename = "map_1500.dat"
        message_key = "MAP_UPLOAD_EXISTING_MAP_LOCKED"

        self.copy_test_data_file("existing_unlocked.dat", self.uploads_dir,
                                 filename)

        original_file_content = self.load_test_data_file(filename)

        first_data = OrderedMultiDict()
        first_data.add("userName", username)
        first_data.add("map", (BytesIO(original_file_content), filename))

        first_response = self.perform_upload(first_data)

        second_data = OrderedMultiDict()
        second_data.add("userName", username)
        second_data.add("map", (BytesIO(original_file_content), filename))

        second_response = self.perform_upload(second_data)

        assert second_response.status_code == 200
        assert second_response.mimetype == "text/html"

        # Verify that the new map file was uploaded and locked,
        # but the "existing file locked" error message appears after second upload
        expected_nbt_file = self.load_test_data_nbt_file(filename)
        uploaded_nbt_file = self.load_uploaded_nbt_file(filename)

        self.verify_matching_nbt_values(expected_nbt_file, uploaded_nbt_file)

        assert get_nbt_map_value(uploaded_nbt_file, "locked") == 1

        self.verify_flash_message_by_key(message_key, second_response.data,
                                         filename)
        mock_logger.warn.assert_called_with(self.get_log_message(message_key),
                                            filename, username)
Esempio n. 33
0
def test_ordered_multidict():
    """Test the OrderedMultiDict"""
    d = OrderedMultiDict()
    assert not d
    d.add('foo', 'bar')
    assert len(d) == 1
    d.add('foo', 'baz')
    assert len(d) == 1
    assert d.items() == [('foo', 'bar')]
    assert list(d) == ['foo']
    assert d.items(multi=True) == [('foo', 'bar'), ('foo', 'baz')]
    del d['foo']
    assert not d
    assert len(d) == 0
    assert list(d) == []

    d.update([('foo', 1), ('foo', 2), ('bar', 42)])
    d.add('foo', 3)
    assert d.getlist('foo') == [1, 2, 3]
    assert d.getlist('bar') == [42]
    assert d.items() == [('foo', 1), ('bar', 42)]
    assert d.keys() == list(d) == list(d.iterkeys()) == ['foo', 'bar']
    assert d.items(multi=True) == [('foo', 1), ('foo', 2), ('bar', 42),
                                   ('foo', 3)]
    assert len(d) == 2

    assert d.pop('foo') == 1
    assert d.pop('blafasel', None) is None
    assert d.pop('blafasel', 42) == 42
    assert len(d) == 1
    assert d.poplist('bar') == [42]
    assert not d

    d.get('missingkey') is None

    d.add('foo', 42)
    d.add('foo', 23)
    d.add('bar', 2)
    d.add('foo', 42)
    assert d == MultiDict(d)
    id = ImmutableOrderedMultiDict(d)
    assert d == id
    d.add('foo', 2)
    assert d != id

    d.update({'blah': [1, 2, 3]})
    assert d['blah'] == 1
    assert d.getlist('blah') == [1, 2, 3]

    # setlist works
    d = OrderedMultiDict()
    d['foo'] = 42
    d.setlist('foo', [1, 2])
    assert d.getlist('foo') == [1, 2]

    assert_raises(OrderedMultiDict.KeyError, d.pop, 'missing')
    assert_raises(OrderedMultiDict.KeyError, d.__getitem__, 'missing')

    # popping
    d = OrderedMultiDict()
    d.add('foo', 23)
    d.add('foo', 42)
    d.add('foo', 1)
    assert d.popitem() == ('foo', 23)
    assert_raises(OrderedMultiDict.KeyError, d.popitem)
    assert not d

    d.add('foo', 23)
    d.add('foo', 42)
    d.add('foo', 1)
    assert d.popitemlist() == ('foo', [23, 42, 1])
    assert_raises(OrderedMultiDict.KeyError, d.popitemlist)
Esempio n. 34
0
 def test_multidict_encoding(self):
     d = OrderedMultiDict()
     d.add('2013-10-10T23:26:05.657975+0000', '2013-10-10T23:26:05.657975+0000')
     self.assert_equal(urls.url_encode(d), '2013-10-10T23%3A26%3A05.657975%2B0000=2013-10-10T23%3A26%3A05.657975%2B0000')
Esempio n. 35
0
def test_ordered_multidict():
    """Test the OrderedMultiDict"""
    d = OrderedMultiDict()
    assert not d
    d.add('foo', 'bar')
    assert len(d) == 1
    d.add('foo', 'baz')
    assert len(d) == 1
    assert d.items() == [('foo', 'bar')]
    assert list(d) == ['foo']
    assert d.items(multi=True) == [('foo', 'bar'),
                                   ('foo', 'baz')]
    del d['foo']
    assert not d
    assert len(d) == 0
    assert list(d) == []

    d.update([('foo', 1), ('foo', 2), ('bar', 42)])
    d.add('foo', 3)
    assert d.getlist('foo') == [1, 2, 3]
    assert d.getlist('bar') == [42]
    assert d.items() == [('foo', 1), ('bar', 42)]
    assert d.keys() == list(d) == list(d.iterkeys()) == ['foo', 'bar']
    assert d.items(multi=True) == [('foo', 1), ('foo', 2),
                                   ('bar', 42), ('foo', 3)]
    assert len(d) == 2

    assert d.pop('foo') == 1
    assert d.pop('blafasel', None) is None
    assert d.pop('blafasel', 42) == 42
    assert len(d) == 1
    assert d.poplist('bar') == [42]
    assert not d

    d.get('missingkey') is None

    d.add('foo', 42)
    d.add('foo', 23)
    d.add('bar', 2)
    d.add('foo', 42)
    assert d == MultiDict(d)
    id = ImmutableOrderedMultiDict(d)
    assert d == id
    d.add('foo', 2)
    assert d != id

    d.update({'blah': [1, 2, 3]})
    assert d['blah'] == 1
    assert d.getlist('blah') == [1, 2, 3]

    # setlist works
    d = OrderedMultiDict()
    d['foo'] = 42
    d.setlist('foo', [1, 2])
    assert d.getlist('foo') == [1, 2]

    assert_raises(OrderedMultiDict.KeyError, d.pop, 'missing')
    assert_raises(OrderedMultiDict.KeyError, d.__getitem__, 'missing')

    # popping
    d = OrderedMultiDict()
    d.add('foo', 23)
    d.add('foo', 42)
    d.add('foo', 1)
    assert d.popitem() == ('foo', 23)
    assert_raises(OrderedMultiDict.KeyError, d.popitem)
    assert not d

    d.add('foo', 23)
    d.add('foo', 42)
    d.add('foo', 1)
    assert d.popitemlist() == ('foo', [23, 42, 1])
    assert_raises(OrderedMultiDict.KeyError, d.popitemlist)
Esempio n. 36
0
def test_ordered_multidict():
    """Test the OrderedMultiDict"""
    d = OrderedMultiDict()
    assert not d
    d.add("foo", "bar")
    assert len(d) == 1
    d.add("foo", "baz")
    assert len(d) == 1
    assert d.items() == [("foo", "bar")]
    assert list(d) == ["foo"]
    assert d.items(multi=True) == [("foo", "bar"), ("foo", "baz")]
    del d["foo"]
    assert not d
    assert len(d) == 0
    assert list(d) == []

    d.update([("foo", 1), ("foo", 2), ("bar", 42)])
    d.add("foo", 3)
    assert d.getlist("foo") == [1, 2, 3]
    assert d.getlist("bar") == [42]
    assert d.items() == [("foo", 1), ("bar", 42)]
    assert d.keys() == list(d) == list(d.iterkeys()) == ["foo", "bar"]
    assert d.items(multi=True) == [("foo", 1), ("foo", 2), ("bar", 42), ("foo", 3)]
    assert len(d) == 2

    assert d.pop("foo") == 1
    assert d.pop("blafasel", None) is None
    assert d.pop("blafasel", 42) == 42
    assert len(d) == 1
    assert d.poplist("bar") == [42]
    assert not d

    d.get("missingkey") is None

    d.add("foo", 42)
    d.add("foo", 23)
    d.add("bar", 2)
    d.add("foo", 42)
    assert d == MultiDict(d)
    id = ImmutableOrderedMultiDict(d)
    assert d == id
    d.add("foo", 2)
    assert d != id

    d.update({"blah": [1, 2, 3]})
    assert d["blah"] == 1
    assert d.getlist("blah") == [1, 2, 3]

    # setlist works
    d = OrderedMultiDict()
    d["foo"] = 42
    d.setlist("foo", [1, 2])
    assert d.getlist("foo") == [1, 2]

    assert_raises(OrderedMultiDict.KeyError, d.pop, "missing")
    assert_raises(OrderedMultiDict.KeyError, d.__getitem__, "missing")

    # popping
    d = OrderedMultiDict()
    d.add("foo", 23)
    d.add("foo", 42)
    d.add("foo", 1)
    assert d.popitem() == ("foo", 23)
    assert_raises(OrderedMultiDict.KeyError, d.popitem)
    assert not d

    d.add("foo", 23)
    d.add("foo", 42)
    d.add("foo", 1)
    assert d.popitemlist() == ("foo", [23, 42, 1])
    assert_raises(OrderedMultiDict.KeyError, d.popitemlist)
Esempio n. 37
0
    def create_request_data(self, map_id):
        data = OrderedMultiDict()
        data.add("mapId", map_id)

        return data
Esempio n. 38
0
class StatementHistory(object):

    """Keeps a history of SQL statements with execution time and offers some pretty printing options.
    No precautions for thread safety.
    """

    def __init__(self):
        self._reset()

    def _reset(self):
        self._statements = OrderedMultiDict()
        self.last_statement = None
        self.last_duration = None
        self.last_timestamp = None

    def append(self, stmt, timestamp, duration, notices):
        self.last_statement = stmt
        self.last_timestamp = timestamp
        self.last_duration = duration
        self.last_notices = notices
        self._statements.add(stmt, (timestamp, duration, notices))

    def clear(self):
        # clear() does not work on OrderedMultiDict, bug in werkzeug?
        self._reset()

    @property
    def statements(self):
        return self._statements.keys()

    @property
    def statements_with_all_infos(self):
        return iteritems(self._statements)
    
    @property
    def statements_with_time(self):
        return ((k, v[0]) for k, v in iteritems(self._statements))

    def format_statement(self, stmt, highlight=True, time=0, duration=0, pygments_style=DEFAULT_PYGMENTS_STYLE, formatter_cls=None):
        show_time = time and duration
        highlight_format_stmt = _make_statement_formatter(show_time, highlight, pygments_style, formatter_cls)
        return highlight_format_stmt(stmt)

    def print_last_statement(self, show_time=True, highlight=True, pygments_style=DEFAULT_PYGMENTS_STYLE):
        if self.last_statement is None:
            print("history is empty")
            return

        highlight_format_stmt = _make_statement_formatter(show_time, highlight, pygments_style)
        print()
        print(highlight_format_stmt(self.last_statement, self.last_timestamp, self.last_duration))

    def print_statements(self, show_time=True, highlight=True, pygments_style=DEFAULT_PYGMENTS_STYLE):
        if self.last_statement is None:
            print("history is empty")
            return

        highlight_format_stmt = _make_statement_formatter(show_time, highlight, pygments_style)
        print()

        for stmt, (timestamp, duration) in self._statements.items(multi=True):
            print(highlight_format_stmt(stmt, timestamp, duration))
Esempio n. 39
0
def test_multidict_encode_decode_text(t1, t2):
    d = OrderedMultiDict()
    d.add(t1, t2)
    assert d == urls.url_decode(urls.url_encode(d))
Esempio n. 40
0
class StatementHistory(object):
    """Keeps a history of SQL statements with execution time and offers some pretty printing options.
    No precautions for thread safety.
    """
    def __init__(self):
        self._reset()

    def _reset(self):
        self._statements = OrderedMultiDict()
        self.last_statement = None
        self.last_duration = None
        self.last_timestamp = None

    def append(self, stmt, timestamp, duration, notices):
        self.last_statement = stmt
        self.last_timestamp = timestamp
        self.last_duration = duration
        self.last_notices = notices
        self._statements.add(stmt, (timestamp, duration, notices))

    def clear(self):
        # clear() does not work on OrderedMultiDict, bug in werkzeug?
        self._reset()

    @property
    def statements(self):
        return self._statements.keys()

    @property
    def statements_with_all_infos(self):
        return iteritems(self._statements)

    @property
    def statements_with_time(self):
        return ((k, v[0]) for k, v in iteritems(self._statements))

    def format_statement(self,
                         stmt,
                         highlight=True,
                         time=0,
                         duration=0,
                         pygments_style=DEFAULT_PYGMENTS_STYLE,
                         formatter_cls=None):
        show_time = time and duration
        highlight_format_stmt = _make_statement_formatter(
            show_time, highlight, pygments_style, formatter_cls)
        return highlight_format_stmt(stmt)

    def print_last_statement(self,
                             show_time=True,
                             highlight=True,
                             pygments_style=DEFAULT_PYGMENTS_STYLE):
        if self.last_statement is None:
            print("history is empty")
            return

        highlight_format_stmt = _make_statement_formatter(
            show_time, highlight, pygments_style)
        print()
        print(
            highlight_format_stmt(self.last_statement, self.last_timestamp,
                                  self.last_duration))

    def print_statements(self,
                         show_time=True,
                         highlight=True,
                         pygments_style=DEFAULT_PYGMENTS_STYLE):
        if self.last_statement is None:
            print("history is empty")
            return

        highlight_format_stmt = _make_statement_formatter(
            show_time, highlight, pygments_style)
        print()

        for stmt, (timestamp, duration) in self._statements.items(multi=True):
            print(highlight_format_stmt(stmt, timestamp, duration))
Esempio n. 41
0
class Form(object):
    """Representation of an HTML form."""

    def __init__(self, parsed):
        parsed = helpers.ensure_soup(parsed)
        if parsed.name != 'form':
            parsed = parsed.find('form')
        self.parsed = parsed
        self.action = self.parsed.get('action')
        self.method = self.parsed.get('method', 'get')
        self.fields = OrderedMultiDict()
        for field in _parse_fields(self.parsed):
            self.add_field(field)

    def add_field(self, field):
        """Add a field.

        :param field: Field to add
        :raise: ValueError if `field` is not an instance of `BaseField`.

        """
        if not isinstance(field, fields.BaseField):
            raise ValueError('Argument "field" must be an instance of '
                             'BaseField')
        self.fields.add(field.name, field)

    @property
    def submit_fields(self):
        return _filter_fields(
            self.fields,
            lambda field: isinstance(field, fields.Submit)
        )

    @encode_if_py2
    def __repr__(self):
        state = u', '.join(
            [
                u'{0}={1}'.format(name, field.value)
                for name, field in self.fields.items(multi=True)
            ]
        )
        if state:
            return u'<RoboForm {0}>'.format(state)
        return u'<RoboForm>'

    def keys(self):
        return self.fields.keys()

    def __getitem__(self, item):
        return self.fields[item]

    def __setitem__(self, key, value):
        self.fields[key].value = value

    def serialize(self, submit=None):
        """Serialize each form field to a Payload container.

        :param Submit submit: Optional `Submit` to click, if form includes
            multiple submits
        :return: Payload instance

        """
        include_fields = prepare_fields(self.fields, self.submit_fields, submit)
        return Payload.from_fields(include_fields)
Esempio n. 42
0
def test_multidict_encode_decode_text(t1, t2):
    d = OrderedMultiDict()
    d.add(t1, t2)
    assert d == urls.url_decode(urls.url_encode(d))