How to use _upload_file method in autotest

Best Python code snippet using autotest_python

test_translationbranchapprover.py

Source:test_translationbranchapprover.py Github

copy

Full Screen

...23 super(TestTranslationBranchApprover, self).setUp()24 self.useFixture(FakeLibrarian())25 self.queue = getUtility(ITranslationImportQueue)26 self.series = self.factory.makeProductSeries()27 def _upload_file(self, upload_path):28 # Put a template or translation file in the import queue.29 return self.queue.addOrUpdateEntry(upload_path,30 self.factory.getUniqueString(), True, self.series.owner,31 productseries=self.series)32 def _createTemplate(self, path, domain, productseries=None):33 # Create a template in the database34 if productseries is None:35 productseries = self.series36 return self.factory.makePOTemplate(37 productseries=productseries,38 name=domain.replace('_', '-'),39 translation_domain=domain,40 path=path)41 def _createApprover(self, file_or_files):42 if not isinstance(file_or_files, (tuple, list)):43 paths = (file_or_files,)44 else:45 paths = file_or_files46 return TranslationBranchApprover(paths, productseries=self.series)47 def test_new_template_approved(self):48 # The approver puts new entries in the Approved state.49 template_path = self.factory.getUniqueString() + u'.pot'50 entry = self._upload_file(template_path)51 self.assertEqual(RosettaImportStatus.NEEDS_REVIEW, entry.status)52 self._createApprover(template_path).approve(entry)53 self.assertEqual(RosettaImportStatus.APPROVED, entry.status)54 def test_new_template_without_domain_in_path_uses_project_name(self):55 # When a template upload for a project has a generic path, it56 # can still be approved. The template will have a name and57 # domain based on the project's name.58 template_path = u'messages.pot'59 entry = self._upload_file(template_path)60 self._createApprover(template_path).approve(entry)61 self.assertEqual(RosettaImportStatus.APPROVED, entry.status)62 self.assertEqual(self.series.product.name, entry.potemplate.name)63 self.assertEqual(64 self.series.product.name, entry.potemplate.translation_domain)65 def test_new_package_template_without_domain_is_not_approved(self):66 # If an upload for a package has no information that a template67 # name or domain could be based on, it is not approved.68 # Template domains for packages must generally be unique for the69 # entire distribution, but in practice it's too variable to70 # figure out here.71 package = self.factory.makeSourcePackage()72 package_kwargs = {73 'distroseries': package.distroseries,74 'sourcepackagename': package.sourcepackagename,75 }76 entry = self.queue.addOrUpdateEntry(77 'messages.pot', self.factory.getUniqueString(), True,78 self.factory.makePerson(), **package_kwargs)79 TranslationBranchApprover(entry.path, **package_kwargs).approve(entry)80 self.assertEqual(RosettaImportStatus.NEEDS_REVIEW, entry.status)81 def test_new_template_not_a_template(self):82 # Only template files will be approved currently.83 path = u'eo.po'84 entry = self._upload_file(path)85 self._createApprover(path).approve(entry)86 self.assertEqual(RosettaImportStatus.NEEDS_REVIEW, entry.status)87 def test_new_template_domain(self):88 # The approver gets the translation domain for the entry from the89 # file path if possible.90 translation_domain = self.factory.getUniqueString()91 template_path = translation_domain + u'.pot'92 entry = self._upload_file(template_path)93 self._createApprover(template_path).approve(entry)94 self.assertEqual(95 translation_domain, entry.potemplate.translation_domain)96 def test_new_template_domain_with_xpi(self):97 # For xpi files, template files are always called "en-US.xpi" so98 # the approver won't use that string for a domain. It'll fall99 # back to the next possibility, which is the directory.100 translation_domain = self.factory.getUniqueString()101 template_path = translation_domain + '/en-US.xpi'102 entry = self._upload_file(template_path)103 self._createApprover(template_path).approve(entry)104 self.assertEqual(105 translation_domain, entry.potemplate.translation_domain)106 def test_template_name(self):107 # The name is derived from the file name and must be a valid name.108 translation_domain = (u'Invalid-Name_with illegal#Characters')109 template_path = translation_domain + u'.pot'110 entry = self._upload_file(template_path)111 self._createApprover(template_path).approve(entry)112 self.assertTrue(valid_name(entry.potemplate.name))113 self.assertEqual(u'invalid-name-withillegalcharacters',114 entry.potemplate.name)115 def test_replace_existing_approved(self):116 # Template files that replace existing entries are approved.117 translation_domain = self.factory.getUniqueString()118 template_path = translation_domain + u'.pot'119 self._createTemplate(template_path, translation_domain)120 entry = self._upload_file(template_path)121 self._createApprover(template_path).approve(entry)122 self.assertEqual(RosettaImportStatus.APPROVED, entry.status)123 def test_replace_existing_potemplate(self):124 # When replacing an existing template, the queue entry is linked125 # to that existing entry.126 translation_domain = self.factory.getUniqueString()127 template_path = translation_domain + u'.pot'128 potemplate = self._createTemplate(template_path, translation_domain)129 entry = self._upload_file(template_path)130 self._createApprover(template_path).approve(entry)131 self.assertEqual(potemplate, entry.potemplate)132 def test_ignore_existing_inactive_potemplate(self):133 # When replacing an existing inactive template, the entry is not134 # approved and no template is created for it.135 translation_domain = self.factory.getUniqueString()136 template_path = translation_domain + u'.pot'137 potemplate = self._createTemplate(template_path, translation_domain)138 potemplate.setActive(False)139 entry = self._upload_file(template_path)140 self._createApprover(template_path).approve(entry)141 self.assertEqual(RosettaImportStatus.NEEDS_REVIEW, entry.status)142 self.assertEqual(None, entry.potemplate)143 def test_replace_existing_any_path(self):144 # If just one template file is found in the tree and just one145 # POTemplate is in the database, the upload is always approved.146 existing_domain = self.factory.getUniqueString()147 existing_path = existing_domain + u'.pot'148 potemplate = self._createTemplate(existing_path, existing_domain)149 template_path = self.factory.getUniqueString() + u'.pot'150 entry = self._upload_file(template_path)151 self._createApprover(template_path).approve(entry)152 self.assertEqual(RosettaImportStatus.APPROVED, entry.status)153 self.assertEqual(potemplate, entry.potemplate)154 def test_replace_existing_generic_path_approved(self):155 # If an upload file has a generic path that does not yield a156 # translation domain, it is still approved if an entry with the157 # same file name exists.158 translation_domain = self.factory.getUniqueString()159 generic_path = u'po/messages.pot'160 self._createTemplate(generic_path, translation_domain)161 entry = self._upload_file(generic_path)162 self._createApprover(generic_path).approve(entry)163 self.assertEqual(RosettaImportStatus.APPROVED, entry.status)164 def test_does_not_replace_domain_if_path_contains_no_useful_name(self):165 # For an upload to a package (where there's no fallback to a166 # product name), if the path contains no meaningful domain name167 # but matches that of an existing template, even though the168 # entry gets approved for import into that template, the169 # existing template's domain name stays as it was.170 generic_path = u'po/messages.pot'171 package = self.factory.makeSourcePackage()172 package_kwargs = {173 'distroseries': package.distroseries,174 'sourcepackagename': package.sourcepackagename,175 }176 template = self.factory.makePOTemplate(**package_kwargs)177 original_domain = template.translation_domain178 entry = self.queue.addOrUpdateEntry(179 generic_path, self.factory.getUniqueString(), True,180 template.owner, potemplate=template, **package_kwargs)181 approver = TranslationBranchApprover(generic_path, **package_kwargs)182 approver.approve(entry)183 self.assertEqual(original_domain, template.translation_domain)184 def test_add_template(self):185 # When adding a template to an existing one it is approved if the186 # approver is told about both template files in the tree.187 existing_domain = self.factory.getUniqueString()188 existing_path = u"%s/%s.pot" % (existing_domain, existing_domain)189 self._createTemplate(existing_path, existing_domain)190 new_domain = self.factory.getUniqueString()191 new_path = u"%s/%s.pot" % (new_domain, new_domain)192 entry = self._upload_file(new_path)193 self._createApprover((existing_path, new_path)).approve(entry)194 self.assertEqual(RosettaImportStatus.APPROVED, entry.status)195 self.assertEqual(new_domain, entry.potemplate.translation_domain)196 def test_upload_multiple_new_templates(self):197 # Multiple new templates can be added using the same198 # TranslationBranchApprover instance.199 pot_path1 = self.factory.getUniqueString() + ".pot"200 pot_path2 = self.factory.getUniqueString() + ".pot"201 entry1 = self._upload_file(pot_path1)202 entry2 = self._upload_file(pot_path2)203 approver = self._createApprover((pot_path1, pot_path2))204 approver.approve(entry1)205 self.assertEqual(RosettaImportStatus.APPROVED, entry1.status)206 approver.approve(entry2)207 self.assertEqual(RosettaImportStatus.APPROVED, entry2.status)208 def test_duplicate_template_name(self):209 # If two templates in the branch indicate the same translation210 # domain, they are in conflict and will not be approved.211 pot_path1 = "po/foo_domain.pot"212 pot_path2 = "foo_domain/messages.pot"213 entry1 = self._upload_file(pot_path1)214 entry2 = self._upload_file(pot_path2)215 approver = self._createApprover((pot_path1, pot_path2))216 approver.approve(entry1)217 self.assertEqual(RosettaImportStatus.NEEDS_REVIEW, entry1.status)218 approver.approve(entry2)219 self.assertEqual(RosettaImportStatus.NEEDS_REVIEW, entry2.status)220 def test_approve_only_if_needs_review(self):221 # If an entry is not in NEEDS_REVIEW state, it must not be approved.222 pot_path = self.factory.getUniqueString() + ".pot"223 entry = self._upload_file(pot_path)224 entry.potemplate = self.factory.makePOTemplate()225 not_approve_status = (226 RosettaImportStatus.IMPORTED,227 RosettaImportStatus.DELETED,228 RosettaImportStatus.FAILED,229 RosettaImportStatus.BLOCKED,230 )231 for status in not_approve_status:232 entry.setStatus(233 status, getUtility(ILaunchpadCelebrities).rosetta_experts)234 self._createApprover(pot_path).approve(entry)235 self.assertEqual(status, entry.status)236 def test_approveNewSharingTemplate(self):237 # When the approver creates a new template, the new template238 # gets copies of any existing POFiles for templates that it will239 # share translations with.240 domain = self.factory.getUniqueString()241 pot_path = domain + ".pot"242 trunk = self.series.product.getSeries('trunk')243 trunk_template = self._createTemplate(244 pot_path, domain=domain, productseries=trunk)245 dutch_pofile = self.factory.makePOFile(246 'nl', potemplate=trunk_template)247 entry = self._upload_file(pot_path)248 self._createApprover(pot_path).approve(entry)249 # This really did create a new template.250 self.assertNotEqual(None, entry.potemplate)251 self.assertNotEqual(trunk_template, entry.potemplate)252 self.assertEqual(trunk_template.name, entry.potemplate.name)253 # The new template also has a Dutch translation of its own.254 new_dutch_pofile = entry.potemplate.getPOFileByLang('nl')255 self.assertNotEqual(None, new_dutch_pofile)256 self.assertNotEqual(dutch_pofile, new_dutch_pofile)257class TestBranchApproverPrivileges(TestCaseWithFactory):258 """Test database privileges required for the branch approver.259 Runs the `TranslationsBranchApprover` through a few scenarios that260 exercise its database privileges. This is a slow test because it261 needs to commit a lot; it's not a place to verify anything other...

Full Screen

Full Screen

test_view.py

Source:test_view.py Github

copy

Full Screen

...37 raise RuntimeError("Could not unregister adapter.")38 return False39class TestCase(unittest.TestCase):40 layer = QUICKUPLOAD_FUNCTIONAL_TESTING41 def _upload_file(self, filename, title=None, description=None,42 bodyfile=None):43 from collective.quickupload.browser.quick_upload import QuickUploadFile44 portal = self.layer['portal']45 request = TestRequest()46 # We need a RESPONSE object.47 request.RESPONSE = request._createResponse()48 # Signal that this is an ajax upload:49 request.HTTP_X_REQUESTED_WITH = 'XHR'50 # Set file name:51 request.HTTP_X_FILE_NAME = filename52 request.BODYFILE = bodyfile or StringIO('dummy file content')53 if title is not None:54 request.form['title'] = title55 if description is not None:56 request.form['description'] = description57 view = QuickUploadFile(portal, request)58 return json.loads(view())59 def test_upload_file_simple(self):60 filename = 'my-file.jpg'61 portal = self.layer['portal']62 setRoles(portal, TEST_USER_ID, ('Manager',))63 result = self._upload_file(filename)64 self.assertEqual(result.get('success'), True)65 self.assertFalse(result.get('error'))66 self.assertEqual(result.get('name'), filename)67 self.assertEqual(result.get('title'), 'my file')68 self.assertTrue(filename in portal)69 image = portal[filename]70 self.assertEqual(image.Title(), 'my file')71 self.assertEqual(result.get('uid'), image.UID())72 def test_upload_file_unauthorized(self):73 filename = 'my-file.jpg'74 portal = self.layer['portal']75 result = self._upload_file(filename)76 self.assertEqual(result.get('error'), 'serverErrorNoPermission')77 self.assertFalse(result.get('success'))78 self.assertFalse(filename in portal)79 def test_upload_file_abort_returns_empty_error(self):80 filename = 'cheese.txt'81 result = self._upload_file(filename, bodyfile=object())82 self.assertEqual({u'error': u'emptyError'}, result)83 def test_upload_empty_file_returns_empty_error(self):84 filename = 'cheese.txt'85 result = self._upload_file(filename, bodyfile=StringIO(''))86 self.assertEqual({u'error': u'emptyError'}, result)87 def test_upload_file_read_error_returns_server_error(self):88 class FailingFile(object):89 def read():90 raise Exception("oops")91 filename = 'parrot.txt'92 result = self._upload_file(filename, bodyfile=FailingFile())93 self.assertEqual({u'error': u'serverError'}, result)94 def test_upload_file_raises_missing_extension_for_invalid_filenames(self):95 filename = 'ni'96 result = self._upload_file(filename)97 self.assertEqual({u'error': u'missingExtension'}, result)98 def test_file_updater_exception_returns_server_error(self):99 class FailingFileUpdater(QuickUploadCapableFileUpdater):100 def __call__(self, *args, **kwargs):101 raise Exception("duh!")102 portal = self.layer['portal']103 setRoles(portal, TEST_USER_ID, ('Manager',))104 props = portal.portal_properties.quickupload_properties105 props._updateProperty('object_unique_id', False)106 props._updateProperty('object_override', True)107 transaction.commit()108 with TemporaryAdapterRegistration(FailingFileUpdater,109 required=(IPloneSiteRoot,),110 provided=IQuickUploadFileUpdater):111 filename = 'qux.txt'112 result = self._upload_file(filename)113 # upload again, force update114 result = self._upload_file(filename)115 self.assertEqual({u'error': u'serverError'}, result)116 def test_file_updater_error_returns_custom_error(self):117 class ErrorFileUpdater(QuickUploadCapableFileUpdater):118 def __call__(self, *args, **kwargs):119 return {"error": "It's stone dead", "success": None}120 portal = self.layer["portal"]121 setRoles(portal, TEST_USER_ID, ("Manager",))122 props = portal.portal_properties.quickupload_properties123 props._updateProperty("object_unique_id", False)124 props._updateProperty("object_override", True)125 transaction.commit()126 with TemporaryAdapterRegistration(ErrorFileUpdater,127 required=(IPloneSiteRoot,),128 provided=IQuickUploadFileUpdater):129 filename = "qux.txt"130 result = self._upload_file(filename)131 # upload again, force update132 result = self._upload_file(filename)133 self.assertEqual({u"error": u"It's stone dead"}, result)134 def test_file_factory_exception_returns_server_error(self):135 class FailingFileFactory(QuickUploadCapableFileFactory):136 def __call__(self, *args, **kwargs):137 raise Exception("nah-ah")138 with TemporaryAdapterRegistration(FailingFileFactory,139 required=(IPloneSiteRoot,),140 provided=IQuickUploadFileFactory):141 filename = 'qux.txt'142 result = self._upload_file(filename)143 self.assertEqual({u'error': u'serverError'}, result)144 def test_file_factory_error_returns_custom_error(self):145 class ErrorFileFactory(QuickUploadCapableFileFactory):146 def __call__(self, *args, **kwargs):147 return {"error": "It's stone dead", "success": None}148 with TemporaryAdapterRegistration(ErrorFileFactory,149 required=(IPloneSiteRoot,),150 provided=IQuickUploadFileFactory):151 filename = "qux.txt"152 result = self._upload_file(filename)153 self.assertEqual({u"error": u"It's stone dead"}, result)154 def test_upload_file_twice_unique_id(self):155 filename = 'my-file.jpg'156 portal = self.layer['portal']157 setRoles(portal, TEST_USER_ID, ('Manager',))158 props = portal.portal_properties.quickupload_properties159 props._updateProperty('object_unique_id', True)160 # We must explicitly commit.161 transaction.commit()162 # Upload twice.163 result = self._upload_file(filename)164 result = self._upload_file(filename, 'title two')165 newid = 'my-file-1.jpg'166 self.assertEqual(result.get('success'), True)167 self.assertEqual(result.get('name'), newid)168 self.assertEqual(result.get('title'), 'title two')169 self.assertTrue(newid in portal)170 image2 = portal[newid]171 self.assertEqual(image2.Title(), 'title two')172 self.assertEqual(result.get('uid'), image2.UID())173 def test_upload_file_twice_override(self):174 filename = 'my-file.jpg'175 portal = self.layer['portal']176 setRoles(portal, TEST_USER_ID, ('Manager',))177 props = portal.portal_properties.quickupload_properties178 props._updateProperty('object_override', True)179 # We must explicitly commit, otherwise the change somehow gets lost180 # between the two uploads, presumably due to the explicit commit in181 # uploadcapable.py.182 transaction.commit()183 # Upload twice.184 result = self._upload_file(filename)185 result = self._upload_file(filename, 'title two')186 newid = 'my-file-1.jpg'187 self.assertEqual(result.get('success'), True)188 self.assertEqual(result.get('name'), filename)189 self.assertEqual(result.get('title'), 'title two')190 self.assertFalse(newid in portal)191 image2 = portal[filename]192 self.assertEqual(image2.Title(), 'title two')193 self.assertEqual(result.get('uid'), image2.UID())194 def test_upload_file_twice_default(self):195 filename = 'my-file.jpg'196 portal = self.layer['portal']197 setRoles(portal, TEST_USER_ID, ('Manager',))198 # Upload twice.199 result = self._upload_file(filename)200 result = self._upload_file(filename, 'title two')201 newid = 'my-file-1.jpg'202 self.assertEqual(result.get('error'), 'serverErrorAlreadyExists')203 self.assertFalse(result.get('success'))204 self.assertFalse(newid in portal)205 self.assertTrue(filename in portal)206 image = portal[filename]207 self.assertEqual(image.Title(), 'my file')208 def test_upload_file_id_as_title(self):209 filename = 'my-file.jpg'210 portal = self.layer['portal']211 setRoles(portal, TEST_USER_ID, ('Manager',))212 props = portal.portal_properties.quickupload_properties213 props._updateProperty('id_as_title', True)214 # We must explicitly commit.215 transaction.commit()216 result = self._upload_file(filename)217 self.assertEqual(result.get('success'), True)218 self.assertEqual(result.get('name'), filename)219 self.assertEqual(result.get('title'), filename)220 self.assertTrue(filename in portal)221 image = portal[filename]222 self.assertEqual(image.Title(), filename)223 def test_upload_explicit_title_and_description(self):224 filename = 'my-file.jpg'225 portal = self.layer['portal']226 setRoles(portal, TEST_USER_ID, ('Manager',))227 # With id_as_title True, an explicit title still wins.228 props = portal.portal_properties.quickupload_properties229 props._updateProperty('id_as_title', True)230 # We must explicitly commit.231 transaction.commit()232 title = 'Monty Python'233 description = 'We are the knights who say ni.'234 result = self._upload_file(filename, title, description)235 self.assertEqual(result.get('success'), True)236 self.assertEqual(result.get('name'), filename)237 self.assertEqual(result.get('title'), title)238 self.assertTrue(filename in portal)239 image = portal[filename]240 self.assertEqual(image.Title(), title)...

Full Screen

Full Screen

test_bulk_import.py

Source:test_bulk_import.py Github

copy

Full Screen

1# pylint: disable=protected-access2from pathlib import Path3from shutil import copy4from typing import Tuple5from unittest.mock import MagicMock6import pytest7from model_bakery import baker8from requests_mock import Mocker9from ....._fixtures import AUDIO_FILENAME, fixture_path10from ....management.commands.bulk_import import Importer11FAKE_URL = "https://somehost.com"12@pytest.fixture(name="import_paths")13def _import_paths(tmp_path: Path):14 sub_dir = tmp_path / "dir1/dir2"15 sub_dir.mkdir(parents=True)16 test_file = sub_dir / AUDIO_FILENAME17 copy(fixture_path / AUDIO_FILENAME, test_file)18 return (tmp_path, test_file)19@pytest.fixture(name="library")20def _library():21 return baker.make(22 "storage.Library",23 code="MUS",24 name="Music",25 description="Some music",26 )27class MockImporter(Importer):28 _handle_file: MagicMock29 _upload_file: MagicMock30 _delete_file: MagicMock31@pytest.fixture(name="importer")32def _importer(requests_mock: Mocker):33 requests_mock.post(f"{FAKE_URL}/rest/media", status_code=200)34 obj: MockImporter = Importer(FAKE_URL, "auth") # type: ignore35 obj._handle_file = MagicMock(wraps=obj._handle_file)36 obj._upload_file = MagicMock(wraps=obj._upload_file)37 obj._delete_file = MagicMock(wraps=obj._delete_file)38 yield obj39@pytest.mark.django_db40def test_importer(41 import_paths: Tuple[Path, Path],42 importer: MockImporter,43 library,44):45 importer.import_dir(import_paths[0], library.code, [".mp3"])46 importer._handle_file.assert_called_with(import_paths[1], library.code)47 importer._upload_file.assert_called_with(import_paths[1], library.code)48 importer._delete_file.assert_not_called()49@pytest.mark.django_db50def test_importer_and_delete(51 import_paths: Tuple[Path, Path],52 importer: MockImporter,53 library,54):55 importer.delete_after_upload = True56 importer.import_dir(import_paths[0], library.code, [".mp3"])57 importer._handle_file.assert_called_with(import_paths[1], library.code)58 importer._upload_file.assert_called_with(import_paths[1], library.code)59 importer._delete_file.assert_called_with(import_paths[1])60@pytest.mark.django_db61def test_importer_existing_file(62 import_paths: Tuple[Path, Path],63 importer: MockImporter,64 library,65):66 baker.make("storage.File", md5="46305a7cf42ee53976c88d337e47e940")67 importer.import_dir(import_paths[0], library.code, [".mp3"])68 importer._handle_file.assert_called_with(import_paths[1], library.code)69 importer._upload_file.assert_not_called()70 importer._delete_file.assert_not_called()71@pytest.mark.django_db72def test_importer_existing_file_and_delete(73 import_paths: Tuple[Path, Path],74 importer: MockImporter,75 library,76):77 baker.make("storage.File", md5="46305a7cf42ee53976c88d337e47e940")78 importer.delete_if_exists = True79 importer.import_dir(import_paths[0], library.code, [".mp3"])80 importer._handle_file.assert_called_with(import_paths[1], library.code)81 importer._upload_file.assert_not_called()82 importer._delete_file.assert_called_with(import_paths[1])83@pytest.mark.django_db84def test_importer_missing_library(85 import_paths: Tuple[Path, Path],86 importer: MockImporter,87):88 with pytest.raises(89 ValueError,90 match="provided library MISSING does not exist",91 ):...

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 autotest 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