Best Python code snippet using avocado_python
test_driver.py
Source:test_driver.py  
1#    Licensed under the Apache License, Version 2.0 (the "License"); you may2#    not use this file except in compliance with the License. You may obtain3#    a copy of the License at4#5#         http://www.apache.org/licenses/LICENSE-2.06#7#    Unless required by applicable law or agreed to in writing, software8#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT9#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the10#    License for the specific language governing permissions and limitations11#    under the License.12from unittest import mock13from oslo_serialization import jsonutils14from oslo_utils import uuidutils15from zun.common import exception16from zun.common import utils17import zun.conf18from zun.tests import base19from zun.volume import driver20CONF = zun.conf.CONF21class CinderVolumeDriverTestCase(base.TestCase):22    def setUp(self):23        super(CinderVolumeDriverTestCase, self).setUp()24        self.fake_uuid = uuidutils.generate_uuid()25        self.fake_volume_id = 'fake-volume-id'26        self.fake_devpath = '/fake-path'27        self.fake_mountpoint = '/fake-mountpoint'28        self.fake_container_path = '/fake-container-path'29        self.fake_conn_info = {30            'data': {'device_path': self.fake_devpath},31        }32        self.volmap = mock.MagicMock()33        self.volmap.volume.uuid = self.fake_uuid34        self.volmap.volume_provider = 'cinder'35        self.volmap.volume_id = self.fake_volume_id36        self.volmap.container_path = self.fake_container_path37        self.volmap.connection_info = jsonutils.dumps(self.fake_conn_info)38    @mock.patch('zun.common.mount.do_mount')39    @mock.patch('oslo_utils.fileutils.ensure_tree')40    @mock.patch('zun.common.mount.get_mountpoint')41    @mock.patch('zun.volume.cinder_workflow.CinderWorkflow')42    def test_attach(self, mock_cinder_workflow_cls, mock_get_mountpoint,43                    mock_ensure_tree, mock_do_mount):44        mock_cinder_workflow = mock.MagicMock()45        mock_cinder_workflow_cls.return_value = mock_cinder_workflow46        mock_cinder_workflow.attach_volume.return_value = self.fake_devpath47        mock_get_mountpoint.return_value = self.fake_mountpoint48        volume_driver = driver.Cinder()49        self.volmap.connection_info = None50        volume_driver.attach(self.context, self.volmap)51        mock_cinder_workflow.attach_volume.assert_called_once_with(self.volmap)52        mock_get_mountpoint.assert_called_once_with(self.fake_uuid)53        mock_do_mount.assert_called_once_with(54            self.fake_devpath, self.fake_mountpoint, CONF.volume.fstype)55        mock_cinder_workflow.detach_volume.assert_not_called()56    @mock.patch('zun.common.mount.do_mount')57    @mock.patch('oslo_utils.fileutils.ensure_tree')58    @mock.patch('zun.common.mount.get_mountpoint')59    @mock.patch('zun.volume.cinder_workflow.CinderWorkflow')60    def test_attach_unknown_provider(self, mock_cinder_workflow_cls,61                                     mock_get_mountpoint, mock_ensure_tree,62                                     mock_do_mount):63        volume_driver = driver.Cinder()64        self.volmap.volume_provider = 'unknown'65        self.assertRaises(exception.ZunException,66                          volume_driver.attach, self.context, self.volmap)67    @mock.patch('zun.common.mount.do_mount')68    @mock.patch('oslo_utils.fileutils.ensure_tree')69    @mock.patch('zun.common.mount.get_mountpoint')70    @mock.patch('zun.volume.cinder_workflow.CinderWorkflow')71    def test_attach_fail_attach(self, mock_cinder_workflow_cls,72                                mock_get_mountpoint, mock_ensure_tree,73                                mock_do_mount):74        mock_cinder_workflow = mock.MagicMock()75        mock_cinder_workflow_cls.return_value = mock_cinder_workflow76        mock_cinder_workflow.attach_volume.side_effect = \77            exception.ZunException()78        mock_get_mountpoint.return_value = self.fake_mountpoint79        volume_driver = driver.Cinder()80        self.volmap.connection_info = None81        self.assertRaises(exception.ZunException,82                          volume_driver.attach, self.context, self.volmap)83        mock_cinder_workflow.attach_volume.assert_called_once_with(self.volmap)84        mock_get_mountpoint.assert_not_called()85        mock_do_mount.assert_not_called()86        mock_cinder_workflow.detach_volume.assert_not_called()87    @mock.patch('zun.common.mount.do_mount')88    @mock.patch('oslo_utils.fileutils.ensure_tree')89    @mock.patch('zun.common.mount.get_mountpoint')90    @mock.patch('zun.volume.cinder_workflow.CinderWorkflow')91    def test_attach_fail_mount(self, mock_cinder_workflow_cls,92                               mock_get_mountpoint, mock_ensure_tree,93                               mock_do_mount):94        mock_cinder_workflow = mock.MagicMock()95        mock_cinder_workflow_cls.return_value = mock_cinder_workflow96        mock_cinder_workflow.attach_volume.return_value = self.fake_devpath97        mock_get_mountpoint.return_value = self.fake_mountpoint98        mock_do_mount.side_effect = exception.ZunException()99        volume_driver = driver.Cinder()100        self.volmap.connection_info = None101        self.assertRaises(exception.ZunException,102                          volume_driver.attach, self.context, self.volmap)103        mock_cinder_workflow.attach_volume.assert_called_once_with(self.volmap)104        mock_get_mountpoint.assert_called_once_with(self.fake_uuid)105        mock_do_mount.assert_called_once_with(106            self.fake_devpath, self.fake_mountpoint, CONF.volume.fstype)107        mock_cinder_workflow.detach_volume.assert_called_once_with(108            self.context, self.volmap)109    @mock.patch('zun.common.mount.do_mount')110    @mock.patch('oslo_utils.fileutils.ensure_tree')111    @mock.patch('zun.common.mount.get_mountpoint')112    @mock.patch('zun.volume.cinder_workflow.CinderWorkflow')113    def test_attach_fail_mount_and_detach(self, mock_cinder_workflow_cls,114                                          mock_get_mountpoint,115                                          mock_ensure_tree,116                                          mock_do_mount):117        class TestException1(Exception):118            pass119        class TestException2(Exception):120            pass121        mock_cinder_workflow = mock.MagicMock()122        mock_cinder_workflow_cls.return_value = mock_cinder_workflow123        mock_cinder_workflow.attach_volume.return_value = self.fake_devpath124        mock_get_mountpoint.return_value = self.fake_mountpoint125        mock_do_mount.side_effect = TestException1()126        mock_cinder_workflow.detach_volume.side_effect = TestException2()127        volume_driver = driver.Cinder()128        self.volmap.connection_info = None129        self.assertRaises(TestException1,130                          volume_driver.attach, self.context, self.volmap)131        mock_cinder_workflow.attach_volume.assert_called_once_with(self.volmap)132        mock_get_mountpoint.assert_called_once_with(self.fake_uuid)133        mock_do_mount.assert_called_once_with(134            self.fake_devpath, self.fake_mountpoint, CONF.volume.fstype)135        mock_cinder_workflow.detach_volume.assert_called_once_with(136            self.context, self.volmap)137    @mock.patch('shutil.rmtree')138    @mock.patch('zun.common.mount.do_unmount')139    @mock.patch('zun.common.mount.get_mountpoint')140    @mock.patch('zun.volume.cinder_workflow.CinderWorkflow')141    def test_detach(self, mock_cinder_workflow_cls, mock_get_mountpoint,142                    mock_do_unmount, mock_rmtree):143        mock_cinder_workflow = mock.MagicMock()144        mock_cinder_workflow_cls.return_value = mock_cinder_workflow145        mock_get_mountpoint.return_value = self.fake_mountpoint146        volume_driver = driver.Cinder()147        volume_driver.detach(self.context, self.volmap)148        mock_cinder_workflow.detach_volume.\149            assert_called_once_with(self.context, self.volmap)150        mock_get_mountpoint.assert_called_once_with(self.fake_uuid)151        mock_do_unmount.assert_called_once_with(self.fake_mountpoint)152        mock_rmtree.assert_called_once_with(self.fake_mountpoint)153    @mock.patch('zun.common.mount.get_mountpoint')154    @mock.patch('zun.volume.cinder_workflow.CinderWorkflow')155    def test_bind_mount(self, mock_cinder_workflow_cls, mock_get_mountpoint):156        mock_cinder_workflow = mock.MagicMock()157        mock_cinder_workflow_cls.return_value = mock_cinder_workflow158        mock_get_mountpoint.return_value = self.fake_mountpoint159        volume_driver = driver.Cinder()160        source, destination = volume_driver.bind_mount(161            self.context, self.volmap)162        self.assertEqual(self.fake_mountpoint, source)163        self.assertEqual(self.fake_container_path, destination)164        mock_get_mountpoint.assert_called_once_with(self.fake_uuid)165    @mock.patch('zun.common.mount.get_mountpoint')166    @mock.patch('zun.common.mount.Mounter.read_mounts')167    @mock.patch('zun.volume.cinder_workflow.CinderWorkflow')168    def test_delete(self, mock_cinder_workflow_cls, mock_read_mounts,169                    mock_get_mountpoint):170        mock_cinder_workflow = mock.MagicMock()171        mock_cinder_workflow_cls.return_value = mock_cinder_workflow172        mock_cinder_workflow.delete_volume.return_value = self.fake_volume_id173        mock_get_mountpoint.return_value = self.fake_mountpoint174        volume_driver = driver.Cinder()175        volume_driver.delete(self.context, self.volmap)176        mock_cinder_workflow.delete_volume.assert_called_once_with(self.volmap)177class LocalVolumeDriverTestCase(base.TestCase):178    def setUp(self):179        super(LocalVolumeDriverTestCase, self).setUp()180        self.fake_uuid = uuidutils.generate_uuid()181        self.fake_mountpoint = '/fake-mountpoint'182        self.fake_container_path = '/fake-container-path'183        self.fake_contents = 'fake-contents'184        self.volmap = mock.MagicMock()185        self.volmap.volume.uuid = self.fake_uuid186        self.volmap.volume_provider = 'local'187        self.volmap.container_path = self.fake_container_path188        self.volmap.contents = self.fake_contents189    @mock.patch('oslo_utils.fileutils.ensure_tree')190    @mock.patch('zun.common.mount.get_mountpoint')191    def test_attach(self, mock_get_mountpoint, mock_ensure_tree):192        mock_get_mountpoint.return_value = self.fake_mountpoint193        volume_driver = driver.Local()194        with mock.patch('zun.volume.driver.open', mock.mock_open()195                        ) as mock_open:196            volume_driver.attach(self.context, self.volmap)197        expected_file_path = self.fake_mountpoint + '/' + self.fake_uuid198        mock_open.assert_called_once_with(expected_file_path, 'wb')199        mock_open().write.assert_called_once_with(200            utils.decode_file_data(self.fake_contents))201        mock_get_mountpoint.assert_called_once_with(self.fake_uuid)202    @mock.patch('shutil.rmtree')203    @mock.patch('zun.common.mount.get_mountpoint')204    def test_detach(self, mock_get_mountpoint, mock_rmtree):205        mock_get_mountpoint.return_value = self.fake_mountpoint206        volume_driver = driver.Local()207        volume_driver.detach(self.context, self.volmap)208        mock_get_mountpoint.assert_called_once_with(self.fake_uuid)209        mock_rmtree.assert_called_once_with(self.fake_mountpoint)210    @mock.patch('zun.common.mount.get_mountpoint')211    def test_bind_mount(self, mock_get_mountpoint):212        mock_get_mountpoint.return_value = self.fake_mountpoint213        volume_driver = driver.Local()214        source, destination = volume_driver.bind_mount(215            self.context, self.volmap)216        expected_file_path = self.fake_mountpoint + '/' + self.fake_uuid217        self.assertEqual(expected_file_path, source)218        self.assertEqual(self.fake_container_path, destination)...sdcard.py
Source:sdcard.py  
...14	@staticmethod15	def get_max_size():16		""" Return the maximal size of sdcard """17		if SdCard.is_mounted():18			status = uos.statvfs(SdCard.get_mountpoint())19			return status[1]*status[2]20		else:21			return 022	@staticmethod23	def get_free_size():24		""" Return the free size of sdcard """25		if SdCard.is_mounted():26			status = uos.statvfs(SdCard.get_mountpoint())27			return status[0]*status[3]28		else:29			return 030	@staticmethod31	def is_mounted():32		""" Indicates if the sd card is mounted """33		return SdCard.opened[0]34	@staticmethod35	def get_mountpoint():36		""" Return the mount point """37		return SdCard.mountpoint[0]38	@staticmethod39	def mount(mountpoint = "/sd"):40		""" Mount sd card """41		result = False42		if SdCard.is_mounted() is False and mountpoint != "/" and mountpoint != "":43			if useful.ismicropython():44				try:45					# If the sdcard not already mounted46					if uos.statvfs("/") == uos.statvfs(mountpoint):47						uos.mount(machine.SDCard(), mountpoint)48						SdCard.mountpoint[0] = mountpoint49						SdCard.opened[0]= True50						result = True51				except Exception as err:52					useful.syslog("Cannot mount %s"%mountpoint)53			else:54				SdCard.mountpoint[0] = mountpoint[1:]55				SdCard.opened[0] = True56				result = True57		elif SdCard.is_mounted():58			if useful.ismicropython():59				if mountpoint == SdCard.get_mountpoint():60					result = True61			else:62				result = True63		return result64	@staticmethod65	def create_file(directory, filename, mode="w"):66		""" Create file with directory """67		result = None68		filepath = directory + "/" + filename69		directories = [directory]70		direct = directory71		while 1:72			parts = useful.split(direct)73			if parts[1] == "" or parts[0] == "":74				break75			directories.append(parts[0])76			direct = parts[0]77		if "/" in directories:78			directories.remove("/")79		if SdCard.mountpoint[0] in directories:80			directories.remove(SdCard.mountpoint[0])81		newdirs = []82		for l in range(len(directories)):83			part = directories[:l]84			part.reverse()85			newdirs.append(part)86		directories.reverse()87		newdirs.append(directories)88		for directories in newdirs:89			for direct in directories:90				try:91					uos.mkdir(direct)92				except OSError as err:93					if err.args[0] not in [2,17]:94						useful.syslog(err)95						break96			try:97				result = open(filepath,mode)98				break99			except OSError as err:100				if err.args[0] not in [2,17]:101					useful.syslog(err)102					break103		return result104	@staticmethod105	def save(directory, filename, data):106		""" Save file on sd card """107		result = False108		if SdCard.is_mounted():109			file = None110			try:111				file = SdCard.create_file(SdCard.get_mountpoint() + "/" + directory, filename, "w")112				file.write(data)113				file.close()114				result = True115			except Exception as err:116				useful.syslog(err, "Cannot save %s/%s/%s"%(SdCard.get_mountpoint(), directory, filename))117			finally:118				if file is not None:119					file.close()...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
