How to use mock_listdir method in Nose

Best Python code snippet using nose

xcodebuild_runner_test.py

Source:xcodebuild_runner_test.py Github

copy

Full Screen

1# Copyright 2018 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4"""Unittests for xcodebuild_runner.py."""5import mock6import os7import plistlib8import shutil9import tempfile10import test_runner11import test_runner_test12import xcodebuild_runner13_ROOT_FOLDER_PATH = 'root/folder'14_XCODE_BUILD_VERSION = '10B61'15_DESTINATION = 'platform=iOS Simulator,OS=12.0,name=iPhone X'16_OUT_DIR = 'out/dir'17_XTEST_RUN = '/tmp/temp_file.xctestrun'18_EGTESTS_APP_PATH = '%s/any_egtests.app' % _ROOT_FOLDER_PATH19class XCodebuildRunnerTest(test_runner_test.TestCase):20 """Test case to test xcodebuild_runner."""21 def setUp(self):22 super(XCodebuildRunnerTest, self).setUp()23 self.mock(os.path, 'exists', lambda _: True)24 self.mock(xcodebuild_runner.LaunchCommand, '_copy_screenshots',25 lambda _1, _2, _3: None)26 self.mock(xcodebuild_runner.LaunchCommand, 'summary_log', lambda _: None)27 self.tmpdir = tempfile.mkdtemp()28 def tearDown(self):29 shutil.rmtree(self.tmpdir, ignore_errors=True)30 super(XCodebuildRunnerTest, self).tearDown()31 def fake_launch_attempt(self, obj, statuses):32 attempt = [0]33 info_plist_statuses = {34 'not_started': {35 'Actions': [{'ActionResult': {}}],36 'TestsCount': 0, 'TestsFailedCount': 037 },38 'fail': {39 'Actions': [40 {'ActionResult': {41 'TestSummaryPath': '1_Test/TestSummaries.plist'}42 }43 ],44 'TestsCount': 99,45 'TestsFailedCount': 1},46 'pass': {47 'Actions': [48 {'ActionResult': {49 'TestSummaryPath': '1_Test/TestSummaries.plist'}50 }51 ],52 'TestsCount': 100,53 'TestsFailedCount': 0}54 }55 test_summary = {56 'TestableSummaries': [57 {'TargetName': 'egtests',58 'Tests': [59 {'Subtests': [60 {'Subtests': [61 {'Subtests': [62 {'TestIdentifier': 'passed_test',63 'TestStatus': 'Success'64 }65 ]66 }67 ]68 }69 ]70 }71 ]72 }73 ]74 }75 def the_fake(cmd, attempt_outdir):76 index = attempt[0]77 attempt[0] += 178 self.assertEqual(os.path.join(self.tmpdir, 'attempt_%d' % index),79 attempt_outdir)80 self.assertEqual(1, cmd.count(attempt_outdir))81 os.mkdir(attempt_outdir)82 with open(os.path.join(attempt_outdir, 'Info.plist'), 'w') as f:83 plistlib.writePlist(info_plist_statuses[statuses[index]], f)84 summary_folder = os.path.join(attempt_outdir, '1_Test')85 os.mkdir(summary_folder)86 with open(os.path.join(summary_folder, 'TestSummaries.plist'), 'w') as f:87 plistlib.writePlist(test_summary, f)88 return (-6, 'Output for attempt_%d' % index)89 obj.launch_attempt = the_fake90 def testEgtests_not_found_egtests_app(self):91 self.mock(os.path, 'exists', lambda _: False)92 with self.assertRaises(test_runner.AppNotFoundError):93 xcodebuild_runner.EgtestsApp(_EGTESTS_APP_PATH)94 def testEgtests_not_found_plugins(self):95 egtests = xcodebuild_runner.EgtestsApp(_EGTESTS_APP_PATH)96 self.mock(os.path, 'exists', lambda _: False)97 with self.assertRaises(test_runner.PlugInsNotFoundError):98 egtests._xctest_path()99 @mock.patch('os.listdir', autospec=True)100 def testEgtests_found_xctest(self, mock_listdir):101 mock_listdir.return_value = ['any_egtests.xctest']102 self.assertEqual('/PlugIns/any_egtests.xctest',103 xcodebuild_runner.EgtestsApp(104 _EGTESTS_APP_PATH)._xctest_path())105 @mock.patch('os.listdir', autospec=True)106 def testEgtests_not_found_xctest(self, mock_listdir):107 mock_listdir.return_value = ['some_egtests.xctest']108 egtest = xcodebuild_runner.EgtestsApp(_EGTESTS_APP_PATH)109 with self.assertRaises(test_runner.XCTestPlugInNotFoundError):110 egtest._xctest_path()111 @mock.patch('os.listdir', autospec=True)112 def testEgtests_xctestRunNode_without_filter(self, mock_listdir):113 mock_listdir.return_value = ['any_egtests.xctest']114 egtest_node = xcodebuild_runner.EgtestsApp(115 _EGTESTS_APP_PATH).xctestrun_node()['any_egtests_module']116 self.assertNotIn('OnlyTestIdentifiers', egtest_node)117 self.assertNotIn('SkipTestIdentifiers', egtest_node)118 @mock.patch('os.listdir', autospec=True)119 def testEgtests_xctestRunNode_with_filter_only_identifiers(self,120 mock_listdir):121 mock_listdir.return_value = ['any_egtests.xctest']122 filtered_tests = ['TestCase1/testMethod1', 'TestCase1/testMethod2',123 'TestCase2/testMethod1', 'TestCase1/testMethod2']124 egtest_node = xcodebuild_runner.EgtestsApp(125 _EGTESTS_APP_PATH, filtered_tests=filtered_tests).xctestrun_node()[126 'any_egtests_module']127 self.assertEqual(filtered_tests, egtest_node['OnlyTestIdentifiers'])128 self.assertNotIn('SkipTestIdentifiers', egtest_node)129 @mock.patch('os.listdir', autospec=True)130 def testEgtests_xctestRunNode_with_filter_skip_identifiers(self,131 mock_listdir):132 mock_listdir.return_value = ['any_egtests.xctest']133 skipped_tests = ['TestCase1/testMethod1', 'TestCase1/testMethod2',134 'TestCase2/testMethod1', 'TestCase1/testMethod2']135 egtest_node = xcodebuild_runner.EgtestsApp(136 _EGTESTS_APP_PATH, filtered_tests=skipped_tests,137 invert=True).xctestrun_node()['any_egtests_module']138 self.assertEqual(skipped_tests, egtest_node['SkipTestIdentifiers'])139 self.assertNotIn('OnlyTestIdentifiers', egtest_node)140 @mock.patch('xcodebuild_runner.LaunchCommand.fill_xctest_run', autospec=True)141 def testLaunchCommand_command(self, mock_fill_xctestrun):142 mock_fill_xctestrun.return_value = _XTEST_RUN143 mock_egtest = mock.MagicMock(spec=xcodebuild_runner.EgtestsApp)144 type(mock_egtest).egtests_path = mock.PropertyMock(145 return_value=_EGTESTS_APP_PATH)146 cmd = xcodebuild_runner.LaunchCommand(147 mock_egtest, _DESTINATION, shards=3, retries=1, out_dir=_OUT_DIR)148 self.assertEqual(['xcodebuild', 'test-without-building',149 '-xctestrun', '/tmp/temp_file.xctestrun',150 '-destination',151 'platform=iOS Simulator,OS=12.0,name=iPhone X',152 '-resultBundlePath', 'out/dir',153 '-parallel-testing-enabled', 'YES',154 '-parallel-testing-worker-count', '3'],155 cmd.command(egtests_app=mock_egtest,156 out_dir=_OUT_DIR,157 destination=_DESTINATION,158 shards=3))159 @mock.patch('plistlib.writePlist', autospec=True)160 @mock.patch('os.path.join', autospec=True)161 def testFill_xctest_run(self, mock_path_join, _):162 self._mocks[xcodebuild_runner.LaunchCommand].pop('fill_xctest_run', None)163 mock_path_join.return_value = _XTEST_RUN164 mock_egtest = mock.MagicMock(spec=xcodebuild_runner.EgtestsApp)165 launch_command = xcodebuild_runner.LaunchCommand(166 mock_egtest, _DESTINATION, shards=1, retries=1, out_dir=_OUT_DIR)167 self.assertEqual(_XTEST_RUN, launch_command.fill_xctest_run(mock_egtest))168 self.assertEqual([mock.call.xctestrun_node()], mock_egtest.method_calls)169 def testFill_xctest_run_exception(self):170 with self.assertRaises(test_runner.AppNotFoundError):171 xcodebuild_runner.LaunchCommand([], 'destination', shards=1, retries=1,172 out_dir=_OUT_DIR).fill_xctest_run([])173 @mock.patch('xcodebuild_runner.LaunchCommand.fill_xctest_run', autospec=True)174 def testLaunchCommand_make_cmd_list_for_failed_tests(self,175 fill_xctest_run_mock):176 fill_xctest_run_mock.side_effect = [177 '/var/folders/tmpfile1'178 ]179 egtest_app = 'module_1_egtests.app'180 egtest_app_path = '%s/%s' % (_ROOT_FOLDER_PATH, egtest_app)181 failed_tests = {182 egtest_app: [183 'TestCase1_1/TestMethod1',184 'TestCase1_1/TestMethod2',185 'TestCase1_2/TestMethod1',186 ]187 }188 expected_egtests = xcodebuild_runner.EgtestsApp(189 egtest_app_path, filtered_tests=failed_tests[egtest_app])190 mock_egtest = mock.MagicMock(spec=xcodebuild_runner.EgtestsApp)191 type(mock_egtest).egtests_path = mock.PropertyMock(192 return_value=egtest_app_path)193 cmd = xcodebuild_runner.LaunchCommand(194 egtests_app=mock_egtest,195 destination=_DESTINATION,196 out_dir='out/dir/attempt_2/iPhone X 12.0',197 shards=1,198 retries=1199 )200 cmd._make_cmd_list_for_failed_tests(201 failed_tests, os.path.join(_OUT_DIR, 'attempt_2'))202 self.assertEqual(1, len(fill_xctest_run_mock.mock_calls))203 self.assertItemsEqual(expected_egtests.__dict__,204 fill_xctest_run_mock.mock_calls[0][1][1].__dict__)205 @mock.patch('os.listdir', autospec=True)206 def testLaunchCommand_restartFailed1stAttempt(self, mock_listdir):207 mock_listdir.return_value = ['any_egtests.xctest']208 egtests = xcodebuild_runner.EgtestsApp(_EGTESTS_APP_PATH)209 launch_command = xcodebuild_runner.LaunchCommand(egtests,210 _DESTINATION,211 shards=1,212 retries=3,213 out_dir=self.tmpdir)214 self.fake_launch_attempt(launch_command, ['not_started', 'pass'])215 launch_command.launch()...

Full Screen

Full Screen

languages_test.py

Source:languages_test.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from unittest import TestCase3from unittest.mock import MagicMock4from unittest.mock import patch5from flask_babel import Locale6from app import create_app7from app import db8from app.configuration import TestConfiguration9from app.localization import get_default_language10from app.localization import get_language_names11from app.localization import get_languages12from app.localization import get_locale13from app.userprofile import User14class LanguagesTest(TestCase):15 def setUp(self):16 """17 Initialize the test cases.18 """19 self.app = create_app(TestConfiguration)20 self.app_context = self.app.app_context()21 self.app_context.push()22 self.request_context = self.app.test_request_context()23 self.request_context.push()24 db.create_all()25 self.default_language = 'en'26 self.path = 'mock/test'27 self.listdir_return_value = [28 'de',29 'en-US',30 'not-a-language',31 '12-34',32 'DE',33 'DE-de',34 'de-',35 'de--',36 'de--DE',37 'de-DEE',38 'de-AT-CH',39 '-DE',40 '-',41 '',42 ]43 def tearDown(self):44 """45 Reset the test cases.46 """47 db.session.remove()48 db.drop_all()49 self.request_context.pop()50 self.app_context.pop()51 def test_get_default_language(self):52 """53 Test getting the default language.54 Expected result: 'en' is always returned.55 """56 self.assertEqual(self.default_language, get_default_language())57 @patch('app.localization.languages.listdir')58 def test_get_language_names_with_native_names_english(self, mock_listdir: MagicMock):59 """60 Test getting the list of language names with their native names (with 'en' as locale).61 Expected result: The list is returned and sorted by their name.62 """63 mock_listdir.return_value = [64 'es',65 'fr',66 'de',67 ]68 expected_names = [69 ('en', 'English'),70 ('fr', 'French (français)'),71 ('de', 'German (Deutsch)'),72 ('es', 'Spanish (español)'),73 ]74 names = get_language_names(TestConfiguration.TRANSLATION_DIR)75 mock_listdir.assert_called()76 self.assertListEqual(expected_names, list(names))77 @patch('app.localization.languages.get_current_locale')78 @patch('app.localization.languages.listdir')79 def test_get_language_names_with_native_names_german(self, mock_listdir: MagicMock,80 mock_get_current_locale: MagicMock):81 """82 Test getting the list of language names with their native names (with 'de' as locale).83 Expected result: The list is returned and sorted by their name.84 """85 mock_get_current_locale.return_value = Locale('de')86 mock_listdir.return_value = [87 'es',88 'fr',89 'de',90 ]91 expected_names = [92 ('de', 'Deutsch'),93 ('en', 'Englisch (English)'),94 ('fr', 'Französisch (français)'),95 ('es', 'Spanisch (español)'),96 ]97 names = get_language_names(TestConfiguration.TRANSLATION_DIR)98 mock_listdir.assert_called()99 self.assertListEqual(expected_names, list(names))100 @patch('app.localization.languages.listdir')101 def test_get_language_names_without_native_names(self, mock_listdir: MagicMock):102 """103 Test getting the list of language names without their native names.104 Expected result: The list is returned and sorted by their name.105 """106 mock_listdir.return_value = [107 'es',108 'fr',109 'de',110 ]111 expected_names = [112 ('en', 'English'),113 ('fr', 'French'),114 ('de', 'German'),115 ('es', 'Spanish'),116 ]117 names = get_language_names(TestConfiguration.TRANSLATION_DIR, with_native_names=False)118 mock_listdir.assert_called()119 self.assertListEqual(expected_names, list(names))120 @patch('app.localization.languages.listdir')121 def test_get_languages_default(self, mock_listdir: MagicMock):122 """123 Run the `get_languages()` function with the default language.124 Expected result: A list containing the default `'en'` plus the valid languages from `listdir()`.125 """126 mock_listdir.return_value = self.listdir_return_value127 languages = get_languages(self.path)128 mock_listdir.assert_called_with(self.path)129 self.assertListEqual([self.default_language, 'de', 'en-US'], list(languages))130 @patch('app.localization.languages.listdir')131 def test_get_languages_non_default(self, mock_listdir: MagicMock):132 """133 Run the `get_languages()` function with a non-default language.134 Expected result: A list containing the non-default language plus the valid languages from `listdir()`.135 """136 mock_listdir.return_value = self.listdir_return_value137 languages = get_languages(self.path, 'fr')138 mock_listdir.assert_called_with(self.path)139 self.assertListEqual(['fr', 'de', 'en-US'], list(languages))140 @patch('app.localization.languages.listdir')141 def test_get_languages_nonexistent_path(self, mock_listdir: MagicMock):142 """143 Run the get_languages() function with a non-existent path (and default language).144 Expected result: A list simply containing the default language, no errors.145 """146 mock_listdir.side_effect = OSError147 languages = get_languages(self.path)148 self.assertListEqual([self.default_language], list(languages))149 @patch('app.localization.languages.request')150 def test_get_locale_from_user(self, mock_request: MagicMock):151 """152 Test getting the locale from a user who is logged in.153 Expected result: The user's preferred language is returned.154 """155 # Mock the best_match() function to ensure it is not called.156 mock_request.accept_languages = MagicMock()157 mock_request.accept_languages.best_match = MagicMock(return_value='de')158 email = 'test@example.com'159 name = 'Jane Doe'160 password = '123456'161 user = User(email, name)162 user.set_password(password)163 db.session.add(user)164 db.session.commit()165 user.login(email, password)166 user.settings._language = 'fr'167 language = get_locale()168 self.assertEqual(user.settings._language, language)169 mock_request.accept_languages.best_match.assert_not_called()170 @patch('app.localization.languages.request')171 def test_get_locale_from_request(self, mock_request: MagicMock):172 """173 Test getting the locale if a user is not logged in.174 Expected result: 'de'.175 """176 mock_request.accept_languages = MagicMock()177 mock_request.accept_languages.best_match = MagicMock(return_value='de')178 language = get_locale()...

Full Screen

Full Screen

test_utils.py

Source:test_utils.py Github

copy

Full Screen

1# Copyright (c) 2013 Intel, Inc.2# Copyright (c) 2012 OpenStack Foundation3# All Rights Reserved.4#5# Licensed under the Apache License, Version 2.0 (the "License"); you may6# not use this file except in compliance with the License. You may obtain7# a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14# License for the specific language governing permissions and limitations15# under the License.16import glob17import os18import mock19from nova import exception20from nova.pci import utils21from nova import test22class PciDeviceMatchTestCase(test.NoDBTestCase):23 def setUp(self):24 super(PciDeviceMatchTestCase, self).setUp()25 self.fake_pci_1 = {'vendor_id': 'v1',26 'device_id': 'd1'}27 def test_single_spec_match(self):28 self.assertTrue(utils.pci_device_prop_match(29 self.fake_pci_1, [{'vendor_id': 'v1', 'device_id': 'd1'}]))30 def test_multiple_spec_match(self):31 self.assertTrue(utils.pci_device_prop_match(32 self.fake_pci_1,33 [{'vendor_id': 'v1', 'device_id': 'd1'},34 {'vendor_id': 'v3', 'device_id': 'd3'}]))35 def test_spec_dismatch(self):36 self.assertFalse(utils.pci_device_prop_match(37 self.fake_pci_1,38 [{'vendor_id': 'v4', 'device_id': 'd4'},39 {'vendor_id': 'v3', 'device_id': 'd3'}]))40 def test_spec_extra_key(self):41 self.assertFalse(utils.pci_device_prop_match(42 self.fake_pci_1,43 [{'vendor_id': 'v1', 'device_id': 'd1', 'wrong_key': 'k1'}]))44class PciDeviceAddressParserTestCase(test.NoDBTestCase):45 def test_parse_address(self):46 self.parse_result = utils.parse_address("0000:04:12.6")47 self.assertEqual(self.parse_result, ('0000', '04', '12', '6'))48 def test_parse_address_wrong(self):49 self.assertRaises(exception.PciDeviceWrongAddressFormat,50 utils.parse_address, "0000:04.12:6")51 def test_parse_address_invalid_character(self):52 self.assertRaises(exception.PciDeviceWrongAddressFormat,53 utils.parse_address, "0000:h4.12:6")54class GetFunctionByIfnameTestCase(test.NoDBTestCase):55 @mock.patch.object(os, 'readlink')56 @mock.patch.object(os, 'listdir')57 def test_virtual_function(self, mock_listdir, mock_readlink):58 mock_listdir.return_value = ['foo', 'bar']59 mock_readlink.return_value = '../../../0000.00.00.1'60 address, physical_function = utils.get_function_by_ifname('eth0')61 self.assertEqual(address, '0000.00.00.1')62 self.assertFalse(physical_function)63 @mock.patch.object(os, 'readlink')64 @mock.patch.object(os, 'listdir')65 def test_physical_function(self, mock_listdir, mock_readlink):66 mock_listdir.return_value = ['foo', 'virtfn1', 'bar']67 mock_readlink.return_value = '../../../0000:00:00.1'68 address, physical_function = utils.get_function_by_ifname('eth0')69 self.assertEqual(address, '0000:00:00.1')70 self.assertTrue(physical_function)71 @mock.patch.object(os, 'listdir')72 def test_exception(self, mock_listdir):73 mock_listdir.side_effect = OSError('No such file or directory')74 address, physical_function = utils.get_function_by_ifname('lo')75 self.assertIsNone(address)76 self.assertFalse(physical_function)77class IsPhysicalFunctionTestCase(test.NoDBTestCase):78 class FakePciAddress(object):79 def __init__(self):80 self.domain = 081 self.bus = 082 self.slot = 083 self.func = 084 def setUp(self):85 super(IsPhysicalFunctionTestCase, self).setUp()86 self.pci_address = self.FakePciAddress()87 @mock.patch.object(os, 'listdir')88 def test_virtual_function(self, mock_listdir):89 mock_listdir.return_value = ['foo', 'bar']90 self.assertFalse(utils.is_physical_function(self.pci_address))91 @mock.patch.object(os, 'listdir')92 def test_physical_function(self, mock_listdir):93 mock_listdir.return_value = ['foo', 'virtfn1', 'bar']94 self.assertTrue(utils.is_physical_function(self.pci_address))95 @mock.patch.object(os, 'listdir')96 def test_exception(self, mock_listdir):97 mock_listdir.side_effect = OSError('No such file or directory')98 self.assertFalse(utils.is_physical_function(self.pci_address))99class GetIfnameByPciAddressTestCase(test.NoDBTestCase):100 def setUp(self):101 super(GetIfnameByPciAddressTestCase, self).setUp()102 self.pci_address = '0000:00:00.1'103 @mock.patch.object(os, 'listdir')104 def test_physical_function_inferface_name(self, mock_listdir):105 mock_listdir.return_value = ['foo', 'bar']106 ifname = utils.get_ifname_by_pci_address(107 self.pci_address, pf_interface=True)108 self.assertEqual(ifname, 'bar')109 @mock.patch.object(os, 'listdir')110 def test_virtual_function_inferface_name(self, mock_listdir):111 mock_listdir.return_value = ['foo', 'bar']112 ifname = utils.get_ifname_by_pci_address(113 self.pci_address, pf_interface=False)114 self.assertEqual(ifname, 'bar')115 @mock.patch.object(os, 'listdir')116 def test_exception(self, mock_listdir):117 mock_listdir.side_effect = OSError('No such file or directory')118 self.assertRaises(119 exception.PciDeviceNotFoundById,120 utils.get_ifname_by_pci_address,121 self.pci_address122 )123class GetVfNumByPciAddressTestCase(test.NoDBTestCase):124 def setUp(self):125 super(GetVfNumByPciAddressTestCase, self).setUp()126 self.pci_address = '0000:00:00.1'127 self.paths = [128 '/sys/bus/pci/devices/0000:00:00.1/physfn/virtfn3',129 ]130 @mock.patch.object(os, 'readlink')131 @mock.patch.object(glob, 'iglob')132 def test_vf_number_found(self, mock_iglob, mock_readlink):133 mock_iglob.return_value = self.paths134 mock_readlink.return_value = '../../0000:00:00.1'135 vf_num = utils.get_vf_num_by_pci_address(self.pci_address)136 self.assertEqual(vf_num, '3')137 @mock.patch.object(os, 'readlink')138 @mock.patch.object(glob, 'iglob')139 def test_vf_number_not_found(self, mock_iglob, mock_readlink):140 mock_iglob.return_value = self.paths141 mock_readlink.return_value = '../../0000:00:00.2'142 self.assertRaises(143 exception.PciDeviceNotFoundById,144 utils.get_vf_num_by_pci_address,145 self.pci_address146 )147 @mock.patch.object(os, 'readlink')148 @mock.patch.object(glob, 'iglob')149 def test_exception(self, mock_iglob, mock_readlink):150 mock_iglob.return_value = self.paths151 mock_readlink.side_effect = OSError('No such file or directory')152 self.assertRaises(153 exception.PciDeviceNotFoundById,154 utils.get_vf_num_by_pci_address,155 self.pci_address...

Full Screen

Full Screen

test_timelapse_helpers.py

Source:test_timelapse_helpers.py Github

copy

Full Screen

1# coding=utf-82from __future__ import absolute_import3__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'4__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"5import unittest6import mock7import os8import time9from collections import namedtuple10_stat = namedtuple("StatResult", "st_size, st_ctime, st_mtime")11import octoprint.settings12import octoprint.timelapse13class TimelapseTest(unittest.TestCase):14 def setUp(self):15 # mock settings16 self.settings_patcher = mock.patch("octoprint.timelapse.settings")17 self.settings_getter = self.settings_patcher.start()18 self.settings = mock.create_autospec(octoprint.settings.Settings)19 self.settings_getter.return_value = self.settings20 self.now = time.time()21 def cleanUp(self):22 self.settings_patcher.stop()23 @mock.patch("os.remove")24 @mock.patch("os.listdir")25 def test_delete_unrendered_timelapse(self, mock_listdir, mock_remove):26 ## prepare27 mocked_path = "/path/to/timelapse/tmp"28 mocked_files = ["a-0.jpg",29 "a-1.jpg",30 "a-2.jpg",31 "b-0.jpg",32 "b-1.jpg",33 "tmp_00000.jpg",34 "tmp_00001.jpg"]35 self.settings.getBaseFolder.return_value = mocked_path36 mock_listdir.return_value = mocked_files37 ## test38 octoprint.timelapse.delete_unrendered_timelapse("b")39 ## verify40 expected_deletions = map(lambda x: os.path.join(mocked_path, x), ["b-0.jpg",41 "b-1.jpg"])42 expected_deletion_calls = map(mock.call, expected_deletions)43 self.assertListEqual(mock_remove.mock_calls, expected_deletion_calls)44 @mock.patch("time.time")45 @mock.patch("os.remove")46 @mock.patch("os.path.getmtime")47 @mock.patch("os.listdir")48 def test_delete_old_unrendered_timelapses(self, mock_listdir, mock_mtime, mock_remove, mock_time):49 ## prepare50 mocked_path = "/path/to/timelapse/tmp"51 mocked_files = ["old-0.jpg",52 "old-1.jpg",53 "old-2.jpg",54 "prefix-0.jpg",55 "prefix-1.jpg",56 "tmp_00000.jpg",57 "tmp_00001.jpg"]58 now = self.now59 days = 160 def mtime(p):61 if p.startswith(os.path.join(mocked_path, "old-0")):62 # old-0 is definitely older than cutoff63 return 064 else:65 # all other files were just created66 return now67 self.settings.getBaseFolder.return_value = mocked_path68 self.settings.getInt.return_value = days69 mock_time.return_value = now70 mock_listdir.return_value = mocked_files71 mock_mtime.side_effect = mtime72 ## test73 octoprint.timelapse.delete_old_unrendered_timelapses()74 ## verify75 expected_deletions = map(lambda x: os.path.join(mocked_path, x), ["tmp_00000.jpg",76 "tmp_00001.jpg",77 "old-0.jpg",78 "old-1.jpg",79 "old-2.jpg"])80 expected_deletion_calls = map(mock.call, expected_deletions)81 self.assertListEqual(mock_remove.mock_calls, expected_deletion_calls)82 @mock.patch("os.stat")83 @mock.patch("os.listdir")84 def test_get_finished_timelapses(self, mock_listdir, mock_stat):85 ## prepare86 files = dict()87 files["one.mpg"] = _stat(st_size=1024, st_ctime=self.now, st_mtime=self.now)88 files["nope.jpg"] = _stat(st_size=100, st_ctime=self.now, st_mtime=self.now)89 files["two.mpg"] = _stat(st_size=2048, st_ctime=self.now, st_mtime=self.now)90 mocked_path = "/path/to/timelapse"91 self.settings.getBaseFolder.return_value = mocked_path92 mock_listdir.return_value = sorted(files.keys())93 def stat(p):94 name = p[len(mocked_path) + 1:]95 return files[name]96 mock_stat.side_effect = stat97 ## test98 result = octoprint.timelapse.get_finished_timelapses()99 ## verify100 self.assertEqual(len(result), 2)101 self.assertEqual(result[0]["name"], "one.mpg")102 self.assertEqual(result[0]["bytes"], 1024)103 self.assertEqual(result[1]["name"], "two.mpg")104 self.assertEqual(result[1]["bytes"], 2048)105 @mock.patch("os.stat")106 @mock.patch("os.listdir")107 def test_unrendered_timelapses(self, mock_listdir, mock_stat):108 ## prepare109 files = dict()110 files["one-0.jpg"] = _stat(st_size=1, st_ctime=self.now - 1, st_mtime=self.now - 1)111 files["one-1.jpg"] = _stat(st_size=2, st_ctime=self.now, st_mtime=self.now)112 files["one-2.jpg"] = _stat(st_size=3, st_ctime=self.now, st_mtime=self.now)113 files["nope.mpg"] = _stat(st_size=2048, st_ctime=self.now, st_mtime=self.now)114 files["two-0.jpg"] = _stat(st_size=4, st_ctime=self.now, st_mtime=self.now)115 files["two-1.jpg"] = _stat(st_size=5, st_ctime=self.now, st_mtime=self.now)116 mocked_path = "/path/to/timelapse/tmp"117 self.settings.getBaseFolder.return_value = mocked_path118 mock_listdir.return_value = sorted(files.keys())119 def stat(p):120 name = p[len(mocked_path) + 1:]121 return files[name]122 mock_stat.side_effect = stat123 ## test124 result = octoprint.timelapse.get_unrendered_timelapses()125 ## verify126 self.assertEqual(len(result), 2)127 self.assertEqual(result[0]["name"], "one")128 self.assertEqual(result[0]["count"], 3)129 self.assertEqual(result[0]["bytes"], 6)130 self.assertEqual(result[1]["name"], "two")131 self.assertEqual(result[1]["count"], 2)...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Nose automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful