Add validation hooks tests

Change-Id: I44260f412c81a19a71f5a854f355dbcc8d8f9d56
This commit is contained in:
Mike Fedosin 2017-07-05 13:29:34 +03:00
parent 14a0fb1c90
commit 5da4af347c
6 changed files with 300 additions and 6 deletions

View File

@ -40,10 +40,10 @@ def create_temporary_file(stream, suffix=''):
tfd, path = tempfile.mkstemp(suffix=suffix)
while True:
data = stream.read(100000)
if data == '': # end of file reached
if data == b'': # end of file reached
break
os.write(tfd, data)
tfile = os.fdopen(tfd)
tfile = os.fdopen(tfd, "rb")
return tfile, path

View File

@ -0,0 +1,105 @@
# Copyright 2017 - Nokia Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import shutil
from oslo_config import cfg
from oslo_log import log as logging
from oslo_versionedobjects import fields
from glare.common import exception
from glare.objects import base
from glare.objects.meta import file_utils
from glare.objects.meta import wrappers
Field = wrappers.Field.init
Dict = wrappers.DictField.init
List = wrappers.ListField.init
Blob = wrappers.BlobField.init
Folder = wrappers.FolderField.init
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class HookChecker(base.BaseArtifact):
fields = {
'zip': Blob(description="Original zipped data.",
required_on_activate=False),
'content': Folder(system=True, required_on_activate=False),
'forbid_activate': Field(fields.FlexibleBooleanField,
default=False),
'forbid_publish': Field(fields.FlexibleBooleanField,
default=False, mutable=True),
'forbid_download_zip': Field(fields.FlexibleBooleanField,
default=False),
'forbid_delete': Field(fields.FlexibleBooleanField,
default=False, mutable=True)
}
@classmethod
def get_type_name(cls):
return "hooks_artifact"
@classmethod
def validate_upload(cls, context, af, field_name, fd):
path = None
tdir = None
try:
tfile, path = file_utils.create_temporary_file(fd, '.zip')
tdir = file_utils.extract_zip_to_temporary_folder(tfile)
# upload all files to 'content' folder
for subdir, dirs, files in os.walk(tdir):
for file_name in files:
path_to_file = os.path.join(subdir, file_name)
with open(path_to_file, "rb") as f:
file_utils.upload_content_file(
context, af, f, 'content',
path_to_file[len(tdir) + 1:])
except Exception as e:
if path is not None and os.path.exists(path):
# remove temporary file if something went wrong
os.remove(path)
raise e
finally:
# remove temporary folder
if tdir is not None:
shutil.rmtree(tdir)
tfile.flush()
tfile.seek(0)
return tfile, path
@classmethod
def validate_download(cls, context, af, field_name, fd):
if af.forbid_download_zip and field_name == 'zip':
raise exception.BadRequest
return fd, None
@classmethod
def validate_activate(cls, context, af):
if af.forbid_activate:
raise exception.BadRequest
@classmethod
def validate_publish(cls, context, af):
if af.forbid_publish:
raise exception.BadRequest
@classmethod
def validate_delete(cls, context, af):
if af.forbid_delete:
raise exception.BadRequest

View File

@ -77,10 +77,14 @@ class BaseTestCase(testtools.TestCase):
enf.rules[default.name] = default.check
self.config(
custom_artifact_types_modules=['glare.tests.sample_artifact'],
custom_artifact_types_modules=[
'glare.tests.sample_artifact',
'glare.tests.hooks_artifact'
],
enabled_artifact_types=[
'sample_artifact:database', 'images', 'heat_templates',
'heat_environments', 'murano_packages', 'tosca_templates']
'hooks_artifact', 'sample_artifact:database', 'images',
'heat_templates', 'heat_environments', 'murano_packages',
'tosca_templates']
)
location.SCHEME_TO_CLS_MAP = {}

View File

@ -24,7 +24,8 @@ class TestMultistore(base.BaseTestCase):
'heat_templates': 'rbd', 'heat_environments': '',
'tosca_templates': 'sheepdog',
'murano_packages': 'vmware_store',
'sample_artifact': 'database'}
'sample_artifact': 'database',
'hooks_artifact': 'database'}
self.config(
enabled_artifact_types=[":".join(_) for _ in types.items()])

View File

@ -0,0 +1,184 @@
# Copyright 2017 - Nokia Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from glare.common import exception as exc
from glare.tests.unit import base
class TestArtifactHooks(base.BaseTestArtifactAPI):
def setUp(self):
super(TestArtifactHooks, self).setUp()
values = {'name': 'ttt', 'version': '1.0'}
self.hooks_artifact = self.controller.create(
self.req, 'hooks_artifact', values)
def test_upload_hook(self):
var_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),
'../', 'var'))
data_path = os.path.join(var_dir, 'hooks.zip')
with open(data_path, "rb") as data:
self.controller.upload_blob(
self.req, 'hooks_artifact', self.hooks_artifact['id'], 'zip',
data, 'application/octet-stream')
artifact = self.controller.show(self.req, 'hooks_artifact',
self.hooks_artifact['id'])
self.assertEqual(818, artifact['zip']['size'])
self.assertEqual('active', artifact['zip']['status'])
self.assertEqual(11, artifact['content']['aaa.txt']['size'])
self.assertEqual(11, artifact['content']['folder1/bbb.txt']['size'])
self.assertEqual(
11, artifact['content']['folder1/folder2/ccc.txt']['size'])
def test_download_hook(self):
# upload data
var_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),
'../', 'var'))
data_path = os.path.join(var_dir, 'hooks.zip')
with open(data_path, "rb") as data:
self.controller.upload_blob(
self.req, 'hooks_artifact', self.hooks_artifact['id'], 'zip',
data, 'application/octet-stream')
# download main 'zip'
data = self.controller.download_blob(
self.req, 'hooks_artifact', self.hooks_artifact['id'],
'zip')['data']
bytes_read = 0
for chunk in data:
bytes_read += len(chunk)
self.assertEqual(818, bytes_read)
# download a file from 'content'
data = self.controller.download_blob(
self.req, 'hooks_artifact', self.hooks_artifact['id'],
'content/folder1/bbb.txt')['data']
bytes_read = 0
for chunk in data:
bytes_read += len(chunk)
self.assertEqual(11, bytes_read)
# now forbid to download zip
changes = [{'op': 'replace', 'path': '/forbid_download_zip',
'value': 'yes'}]
self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
artifact = self.controller.show(self.req, 'hooks_artifact',
self.hooks_artifact['id'])
self.assertEqual(True, artifact['forbid_download_zip'])
# download from 'zip' fails now
self.assertRaises(
exc.BadRequest, self.controller.download_blob,
self.req, 'hooks_artifact', self.hooks_artifact['id'], 'zip')
# download a 'content' file still works
data = self.controller.download_blob(
self.req, 'hooks_artifact', self.hooks_artifact['id'],
'content/folder1/folder2/ccc.txt')['data']
bytes_read = 0
for chunk in data:
bytes_read += len(chunk)
self.assertEqual(11, bytes_read)
def test_activation_hook(self):
# forbid to activate artifact
changes = [{'op': 'replace', 'path': '/forbid_activate',
'value': 'yes'}]
self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
# activation fails now
changes = [{'op': 'replace', 'path': '/status',
'value': 'active'}]
self.assertRaises(
exc.BadRequest, self.update_with_values, changes,
art_type='hooks_artifact', art_id=self.hooks_artifact['id'])
# unblock artifact activation
changes = [{'op': 'replace', 'path': '/forbid_activate',
'value': 'no'}]
self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
# now activation works
changes = [{'op': 'replace', 'path': '/status',
'value': 'active'}]
art = self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
self.assertEqual('active', art['status'])
def test_publishing_hook(self):
self.req = self.get_fake_request(user=self.users['admin'])
# activate artifact to begin
changes = [{'op': 'replace', 'path': '/status',
'value': 'active'}]
art = self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
self.assertEqual('active', art['status'])
# forbid to publish artifact
changes = [{'op': 'replace', 'path': '/forbid_publish',
'value': 'yes'}]
self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
# publication fails now
changes = [{'op': 'replace', 'path': '/visibility',
'value': 'public'}]
self.assertRaises(
exc.BadRequest, self.update_with_values, changes,
art_type='hooks_artifact', art_id=self.hooks_artifact['id'])
# unblock artifact publication
changes = [{'op': 'replace', 'path': '/forbid_publish',
'value': 'no'}]
self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
# now publication works
changes = [{'op': 'replace', 'path': '/visibility',
'value': 'public'}]
art = self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
self.assertEqual('public', art['visibility'])
def test_deletion_hook(self):
# forbid to activate artifact
changes = [{'op': 'replace', 'path': '/forbid_delete',
'value': 'yes'}]
self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
# deletion fails now
self.assertRaises(
exc.BadRequest, self.controller.delete, self.req,
'hooks_artifact', self.hooks_artifact['id'])
# unblock artifact deletion
changes = [{'op': 'replace', 'path': '/forbid_delete',
'value': 'no'}]
self.update_with_values(changes, art_type='hooks_artifact',
art_id=self.hooks_artifact['id'])
# now deletion works
self.controller.delete(self.req, 'hooks_artifact',
self.hooks_artifact['id'])
self.assertRaises(exc.NotFound, self.controller.show, self.req,
'hooks_artifact', self.hooks_artifact['id'])

BIN
glare/tests/var/hooks.zip Normal file

Binary file not shown.