Best Python code snippet using playwright-python
install_checks.py
Source:install_checks.py
...54 self.apps = apps55 self.action = action56 def test(self):57 if self.action == 'install':58 return self._test_install()59 elif self.action == 'upgrade':60 return self._test_upgrade()61 elif self.action == 'remove':62 return self._test_remove()63 return {}64 def _test_install(self):65 return {}66 def _test_upgrade(self):67 return {}68 def _test_remove(self):69 return {}70 @classmethod71 def get_name(cls):72 return underscore(cls.__name__)73 def other_apps(self, app):74 return [_app for _app in self.apps if app != _app]75class SingleRequirement(Requirement):76 def _test_install(self):77 ret = {}78 for app in self.apps:79 result = self.test_install(app)80 if result is not None and result is not True:81 ret[app.id] = result82 return ret83 def test_install(self, app):84 pass85 def _test_upgrade(self):86 ret = {}87 for app in self.apps:88 result = self.test_upgrade(app)89 if result is not None and result is not True:90 ret[app.id] = result91 return ret92 def test_upgrade(self, app):93 pass94 def _test_remove(self):95 ret = {}96 for app in self.apps:97 result = self.test_remove(app)98 if result is not None and result is not True:99 ret[app.id] = result100 return ret101 def test_remove(self, app):102 pass103class MultiRequirement(Requirement):104 def _test_install(self):105 ret = {}106 result = self.test_install(self.apps)107 if result is not None and result is not True:108 ret['__all__'] = result109 return ret110 def test_install(self, apps):111 pass112 def _test_upgrade(self):113 ret = {}114 result = self.test_upgrade(self.apps)115 if result is not None and result is not True:116 ret['__all__'] = result117 return ret118 def test_upgrade(self, apps):119 pass120 def _test_remove(self):121 ret = {}122 result = self.test_remove(self.apps)123 if result is not None and result is not True:124 ret['__all__'] = result125 return ret126 def test_remove(self, apps):127 pass128class HardRequirement(object):129 def is_error(self):130 return True131class SoftRequirement(object):132 def is_error(self):133 return False134class MustHaveCorrectServerRole(SingleRequirement, HardRequirement):135 '''The application cannot be installed on the current server136 role (%(current_role)s). In order to install the application,137 one of the following roles is necessary: %(allowed_roles)r'''138 def test_install(self, app):139 server_role = ucr_get('server/role')140 if not app._allowed_on_local_server():141 return {142 'current_role': server_role,143 'allowed_roles': ', '.join(app.server_role),144 }145 test_upgrade = test_install146class MustHaveFittingAppVersion(SingleRequirement, HardRequirement):147 '''To upgrade, at least version %(required_version)s needs to148 be installed.'''149 def test_upgrade(self, app):150 if app.required_app_version_upgrade:151 required_version = LooseVersion(app.required_app_version_upgrade)152 installed_app = Apps().find(app.id)153 installed_version = LooseVersion(installed_app.version)154 if required_version > installed_version:155 return {'required_version': app.required_app_version_upgrade}156class MustHaveFittingKernelVersion(MultiRequirement, HardRequirement):157 '''The Kernel version has to be upgraded and the system rebootet.'''158 def test_install(self, apps):159 if any(app.docker for app in apps):160 kernel = LooseVersion(os.uname()[2])161 if kernel < LooseVersion('4.9'):162 return False163 test_upgrade = test_install164class MustHaveCandidate(SingleRequirement, HardRequirement):165 '''The application is either not installed or no newer version is available'''166 def test_upgrade(self, app):167 _app = Apps().find(app.id)168 if not _app.is_installed() or _app >= app:169 return False170class MustHaveFittingUcsVersion(SingleRequirement, HardRequirement):171 '''The application requires UCS version %(required_version)s.'''172 def test_install(self, app):173 required_ucs_version = None174 for supported_version in app.supported_ucs_versions:175 if supported_version.startswith('%s-' % ucr_get('version/version')):176 required_ucs_version = supported_version177 break178 else:179 if app.get_ucs_version() == ucr_get('version/version'):180 if app.required_ucs_version:181 required_ucs_version = app.required_ucs_version182 else:183 return True184 if required_ucs_version is None:185 return {'required_version': app.get_ucs_version()}186 major, minor = ucr_get('version/version').split('.', 1)187 patchlevel = ucr_get('version/patchlevel')188 errata = ucr_get('version/erratalevel')189 version_bits = re.match(r'^(\d+)\.(\d+)-(\d+)(?: errata(\d+))?$', required_ucs_version).groups()190 comparisons = zip(version_bits, [major, minor, patchlevel, errata])191 for required, present in comparisons:192 if int(required or 0) > int(present):193 return {'required_version': required_ucs_version}194 if int(required or 0) < int(present):195 return True196 test_upgrade = test_install197class MustHaveInstallPermissions(SingleRequirement, HardRequirement):198 '''You need to buy the App to install this version.'''199 def test_install(self, app):200 if not app.install_permissions_exist():201 return {'shop_url': app.shop_url, 'version': app.version}202 test_upgrade = test_install203class MustHaveNoConflictsApps(SingleRequirement, HardRequirement):204 '''The application conflicts with the following applications:205 %r'''206 def test_install(self, app):207 conflictedapps = set()208 apps_cache = Apps()209 # check ConflictedApps210 for _app in apps_cache.get_all_apps():211 if not _app._allowed_on_local_server():212 # cannot be installed, continue213 continue214 if _app.id in app.conflicted_apps or app.id in _app.conflicted_apps:215 if _app.is_installed():216 conflictedapps.add(_app.id)217 elif _app in self.other_apps(app):218 conflictedapps.add(_app.id)219 # check port conflicts220 ports = []221 for i in app.ports_exclusive:222 ports.append(i)223 for i in app.ports_redirection:224 ports.append(i.split(':', 1)[0])225 for app_id, container_port, host_port in app_ports():226 if app_id != app.id and str(host_port) in ports:227 conflictedapps.add(app_id)228 for _app in self.other_apps(app):229 other_ports = set()230 for i in _app.ports_exclusive:231 other_ports.add(i)232 for i in _app.ports_redirection:233 other_ports.add(i.split(':', 1)[0])234 if other_ports.intersection(ports):235 conflictedapps.add(_app.id)236 if conflictedapps:237 conflictedapps = [apps_cache.find(app_id) for app_id in conflictedapps]238 return [{'id': _app.id, 'name': _app.name} for _app in conflictedapps if _app]239 test_upgrade = test_install240class MustHaveNoConflictsPackages(SingleRequirement, HardRequirement):241 '''The application conflicts with the following packages: %r'''242 def test_install(self, app):243 conflict_packages = []244 for pkgname in app.conflicted_system_packages:245 if packages_are_installed([pkgname], strict=True):246 conflict_packages.append(pkgname)247 if conflict_packages:248 return conflict_packages249 test_upgrade = test_install250class MustHaveNoUnmetDependencies(SingleRequirement, HardRequirement):251 '''The application requires the following applications: %r'''252 def test_install(self, app):253 unmet_apps = []254 apps_cache = Apps()255 # RequiredApps256 for _app in apps_cache.get_all_apps():257 if _app.id in app.required_apps:258 if not _app.is_installed():259 unmet_apps.append({'id': _app.id, 'name': _app.name, 'in_domain': False})260 # RequiredAppsInDomain261 domain = get_action('domain')262 apps = [apps_cache.find(app_id) for app_id in app.required_apps_in_domain]263 apps_info = domain.to_dict(apps)264 for _app in apps_info:265 if not _app:266 continue267 if not _app['is_installed_anywhere']:268 local_allowed = _app['id'] not in app.conflicted_apps269 unmet_apps.append({'id': _app['id'], 'name': _app['name'], 'in_domain': True, 'local_allowed': local_allowed})270 unmet_apps = [unmet_app for unmet_app in unmet_apps if unmet_app['id'] not in (_app.id for _app in self.other_apps(app))]271 if unmet_apps:272 return unmet_apps273 test_upgrade = test_install274class MustHaveSupportedArchitecture(SingleRequirement, HardRequirement):275 '''This application only supports %(supported)s as276 architecture. %(msg)s'''277 def test_install(self, app):278 supported_architectures = app.supported_architectures279 platform_bits = platform.architecture()[0]280 aliases = {'i386': '32bit', 'amd64': '64bit'}281 if supported_architectures:282 for architecture in supported_architectures:283 if aliases[architecture] == platform_bits:284 break285 else:286 # For now only two architectures are supported:287 # 32bit and 64bit - and this will probably not change288 # too soon.289 # So instead of returning lists and whatnot290 # just return a nice message291 # Needs to be adapted when supporting different archs292 supported = supported_architectures[0]293 if supported == 'i386':294 needs = 32295 has = 64296 else:297 needs = 64298 has = 32299 msg = _('The application needs a %(needs)s-bit operating system. This server is running a %(has)s-bit operating system.') % {'needs': needs, 'has': has}300 return {'supported': supported, 'msg': msg}301 test_upgrade = test_install302class MustHaveValidLicense(MultiRequirement, HardRequirement):303 '''For the installation, a UCS license key304 with a key identification (Key ID) is required'''305 def test_install(self, apps):306 if any(app.notify_vendor for app in apps):307 license = ucr_get('uuid/license')308 if license is None:309 ucr_load()310 license = ucr_get('uuid/license')311 return license is not None312 test_upgrade = test_install313class MustNotBeDependedOn(SingleRequirement, HardRequirement):314 '''The application is required for the following applications315 to work: %r'''316 def test_remove(self, app):317 depending_apps = []318 apps_cache = Apps()319 # RequiredApps320 for _app in apps_cache.get_all_apps():321 if app.id in _app.required_apps and _app.is_installed():322 depending_apps.append({'id': _app.id, 'name': _app.name})323 # RequiredAppsInDomain324 apps = [_app for _app in apps_cache.get_all_apps() if app.id in _app.required_apps_in_domain]325 if apps:326 domain = get_action('domain')327 self_info = domain.to_dict([app])[0]328 hostname = ucr_get('hostname')329 if not any(inst['version'] for host, inst in self_info['installations'].items() if host != hostname):330 # this is the only installation331 apps_info = domain.to_dict(apps)332 for _app in apps_info:333 if _app['is_installed_anywhere']:334 depending_apps.append({'id': _app['id'], 'name': _app['name']})335 depending_apps = [depending_app for depending_app in depending_apps if depending_app['id'] not in (_app.id for _app in self.other_apps(app))]336 if depending_apps:337 return depending_apps338class MustNotBeDockerIfDockerIsDisabled(SingleRequirement, HardRequirement):339 '''The application uses a container technology while the App Center340 is configured to not not support it'''341 def test_install(self, app):342 return not app.docker or ucr_is_true('appcenter/docker', True)343 test_upgrade = test_install344class MustNotBeDockerInDocker(SingleRequirement, HardRequirement):345 '''The application uses a container technology while the system346 itself runs in a container. Using the application is not347 supported on this host'''348 def test_install(self, app):349 return not app.docker or not container_mode()350 test_upgrade = test_install351class MustNotBeEndOfLife(SingleRequirement, HardRequirement):352 '''This application was discontinued and may not be installed353 anymore'''354 def test_install(self, app):355 return not app.end_of_life356class MustNotBeInstalled(SingleRequirement, HardRequirement):357 '''This application is already installed'''358 def test_install(self, app):359 return not app.is_installed()360class MustNotBeVoteForApp(SingleRequirement, HardRequirement):361 '''The application is not yet installable. Vote for this app362 now and bring your favorite faster to the Univention App363 Center'''364 def test_install(self, app):365 return not app.vote_for_app366 test_upgrade = test_install367class MustNotHaveConcurrentOperation(SingleRequirement, HardRequirement):368 '''Another package operation is in progress'''369 def test_install(self, app):370 if app.docker:371 return True372 else:373 return get_package_manager().progress_state._finished # TODO: package_manager.is_finished()374 test_upgrade = test_install375 test_remove = test_install376class ShallHaveEnoughFreeDiskSpace(MultiRequirement, SoftRequirement):377 '''The system needs %(minimum)d MB of free disk space but only378 %(current)d MB are available.'''379 def test_install(self, apps):380 required_free_disk_space = 0381 for app in apps:382 required_free_disk_space += (app.min_free_disk_space or 0)383 if required_free_disk_space <= 0:384 return True385 current_free_disk_space = get_free_disk_space()386 if current_free_disk_space and current_free_disk_space < required_free_disk_space:387 return {'minimum': required_free_disk_space, 'current': current_free_disk_space}388class ShallHaveEnoughRam(MultiRequirement, SoftRequirement):389 '''The system need at least %(minimum)d MB of free RAM but only390 %(current)d MB are available.'''391 def test_install(self, apps):392 current_ram = get_current_ram_available()393 required_ram = 0394 for app in apps:395 required_ram += app.min_physical_ram396 if current_ram < required_ram:397 return {'minimum': required_ram, 'current': current_ram}398 def test_upgrade(self, apps):399 current_ram = get_current_ram_available()400 required_ram = 0401 for app in apps:402 required_ram += app.min_physical_ram403 installed_app = Apps().find(app.id)404 # is already installed, just a minor version upgrade405 # RAM "used" by this installed app should count406 # as free. best approach: subtract it407 required_ram -= installed_app.min_physical_ram408 if current_ram < required_ram:409 return {'minimum': required_ram, 'current': current_ram}410class ShallNotBeDockerIfDiscouraged(SingleRequirement, HardRequirement):411 '''The application has not been approved to migrate all412 existing data. Maybe there is a migration guide:413 %(migration_link)s'''414 def test_install(self, app):415 problem = app._docker_prudence_is_true() and not app.docker_migration_works416 if problem:417 return {'migration_link': app.docker_migration_link}418 test_upgrade = test_install419class ShallOnlyBeInstalledInAdEnvWithPasswordService(SingleRequirement, SoftRequirement):420 '''The application requires the password service to be set up421 on the Active Directory domain controller server.'''422 def test_install(self, app):423 return not app._has_active_ad_member_issue('password')424 test_upgrade = test_install425def check(apps, action):426 errors = {}427 warnings = {}428 for name, klass in _REQUIREMENTS.items():429 requirement = klass(apps, action)430 result = requirement.test()431 if result:432 if requirement.is_error():433 errors[name] = result434 else:435 warnings[name] = result436 return errors, warnings...
test_notify_event_sentry_app.py
Source:test_notify_event_sentry_app.py
1from unittest.mock import patch2from exam import before3from rest_framework import serializers4from sentry.rules.actions.notify_event_sentry_app import NotifyEventSentryAppAction5from sentry.tasks.sentry_apps import notify_sentry_app6from sentry.testutils.cases import RuleTestCase7ValidationError = serializers.ValidationError8SENTRY_APP_ALERT_ACTION = "sentry.rules.actions.notify_event_sentry_app.NotifyEventSentryAppAction"9class NotifyEventSentryAppActionTest(RuleTestCase):10 rule_cls = NotifyEventSentryAppAction11 schema_data = [12 {"name": "title", "value": "Squid Game"},13 {"name": "summary", "value": "circle triangle square"},14 ]15 @before16 def create_schema(self):17 self.schema = {"elements": [self.create_alert_rule_action_schema()]}18 def test_applies_correctly_for_sentry_apps(self):19 event = self.get_event()20 self.app = self.create_sentry_app(21 organization=event.organization,22 name="Test Application",23 is_alertable=True,24 schema=self.schema,25 )26 self.install = self.create_sentry_app_installation(27 slug="test-application", organization=event.organization28 )29 rule = self.get_rule(30 data={31 "sentryAppInstallationUuid": self.install.uuid,32 "settings": self.schema_data,33 }34 )35 assert rule.id == SENTRY_APP_ALERT_ACTION36 futures = list(rule.after(event=event, state=self.get_state()))37 assert len(futures) == 138 assert futures[0].callback is notify_sentry_app39 assert futures[0].kwargs["sentry_app"].id == self.app.id40 assert futures[0].kwargs["schema_defined_settings"] == self.schema_data41 @patch("sentry.mediators.sentry_app_components.Preparer.run")42 def test_sentry_app_actions(self, mock_sentry_app_component_preparer):43 event = self.get_event()44 self.project = self.create_project(organization=event.organization)45 self.app = self.create_sentry_app(46 organization=event.organization,47 name="Test Application",48 is_alertable=True,49 schema=self.schema,50 )51 self.install = self.create_sentry_app_installation(52 slug="test-application", organization=event.organization53 )54 rule = self.get_rule(55 data={56 "sentryAppInstallationUuid": self.install.uuid,57 "settings": self.schema_data,58 }59 )60 action_list = rule.get_custom_actions(self.project)61 assert len(action_list) == 162 action = action_list[0]63 alert_element = self.schema["elements"][0]64 assert action["id"] == SENTRY_APP_ALERT_ACTION65 assert action["service"] == self.app.slug66 assert action["prompt"] == self.app.name67 assert action["actionType"] == "sentryapp"68 assert action["enabled"]69 assert action["formFields"] == alert_element["settings"]70 assert alert_element["title"] in action["label"]71 def test_self_validate(self):72 self.organization = self.create_organization()73 self.app = self.create_sentry_app(74 organization=self.organization,75 name="Test Application",76 is_alertable=True,77 schema=self.schema,78 )79 self.install = self.create_sentry_app_installation(80 slug="test-application", organization=self.organization81 )82 # Test no Sentry App Installation uuid83 rule = self.get_rule(data={"hasSchemaFormConfig": True})84 with self.assertRaises(ValidationError):85 rule.self_validate()86 # Test invalid Sentry App Installation uuid87 rule = self.get_rule(88 data={"hasSchemaFormConfig": True, "sentryAppInstallationUuid": "not_a_real_uuid"}89 )90 with self.assertRaises(ValidationError):91 rule.self_validate()92 # Test deleted Sentry App Installation uuid93 test_install = self.create_sentry_app_installation(94 organization=self.organization, slug="test-application"95 )96 test_install.delete()97 rule = self.get_rule(98 data={"hasSchemaFormConfig": True, "sentryAppInstallationUuid": test_install.uuid}99 )100 with self.assertRaises(ValidationError):101 rule.self_validate()102 # Test Sentry Apps without alert rules configured in their schema103 self.create_sentry_app(organization=self.organization, name="No Alert Rule Action")104 test_install = self.create_sentry_app_installation(105 organization=self.organization, slug="no-alert-rule-action"106 )107 rule = self.get_rule(108 data={"hasSchemaFormConfig": True, "sentryAppInstallationUuid": test_install.uuid}109 )110 with self.assertRaises(ValidationError):111 rule.self_validate()112 # Test without providing settings in rule data113 rule = self.get_rule(114 data={"hasSchemaFormConfig": True, "sentryAppInstallationUuid": self.install.uuid}115 )116 with self.assertRaises(ValidationError):117 rule.self_validate()118 # Test without providing required field values119 rule = self.get_rule(120 data={121 "hasSchemaFormConfig": True,122 "sentryAppInstallationUuid": self.install.uuid,123 "settings": [{"name": "title", "value": "Lamy"}],124 }125 )126 with self.assertRaises(ValidationError):127 rule.self_validate()128 # Test with additional fields not on the app's schema129 rule = self.get_rule(130 data={131 "hasSchemaFormConfig": True,132 "sentryAppInstallationUuid": self.install.uuid,133 "settings": [134 {"name": "title", "value": "Lamy"},135 {"name": "summary", "value": "Safari"},136 {"name": "invalidField", "value": "Invalid Value"},137 ],138 }139 )140 with self.assertRaises(ValidationError):141 rule.self_validate()142 # Test with invalid value on Select field143 rule = self.get_rule(144 data={145 "hasSchemaFormConfig": True,146 "sentryAppInstallationUuid": self.install.uuid,147 "settings": [148 {"name": "title", "value": "Lamy"},149 {"name": "summary", "value": "Safari"},150 {"name": "points", "value": "Invalid Select Value"},151 ],152 }153 )154 with self.assertRaises(ValidationError):...
installation.py
Source:installation.py
...46 test_install = stem.util.test_tools.ASYNC_TESTS['test.integ.installation.test_install']47 test_install.run()48 stem.util.test_tools.ASYNC_TESTS['test.integ.installation.test_sdist'].run(test_install.pid())49 @asynchronous50 def test_install():51 """52 Installs with 'python setup.py install' and checks we can use what we53 install.54 """55 try:56 try:57 stem.util.system.call('%s setup.py install --prefix %s' % (PYTHON_EXE, BASE_INSTALL_PATH), timeout = 60, cwd = test.STEM_BASE)58 stem.util.system.call('%s setup.py clean --all' % PYTHON_EXE, timeout = 60, cwd = test.STEM_BASE) # tidy up the build directory59 site_packages_paths = glob.glob('%s/lib*/*/site-packages' % BASE_INSTALL_PATH)60 except Exception as exc:61 raise AssertionError("Unable to install with 'python setup.py install': %s" % exc)62 if len(site_packages_paths) != 1:63 raise AssertionError('We should only have a single site-packages directory, but instead had: %s' % site_packages_paths)64 install_path = site_packages_paths[0]...
__init__.py
Source:__init__.py
...50 import markdown51 except ImportError:52 return self.doc53 return markdown.markdown(self.doc)54 def test_install(self):55 raise NotImplemented56 def test_setup(self):57 return self.test_install()58 @property59 def installed(self):60 return self.test_install() is not False61 @property62 def setup(self):63 return self.test_setup() is not False64class Haystack(Dependency):65 """What's having all this great descriptive data if no one can find it?66 Haystack provides search engine facilities for the metadata.67 Install by doing `pip install django-haystack` and installing one of the68 supported search engine backends. The easiest to setup is Whoosh which is69 implemented in pure Python. Install it by doing `pip install whoosh`. Add70 haystack to `INSTALLED_APPS`.71 """72 name = 'haystack'73 # An import may cause an improperly configured error, so this catches74 # and returns the error for downstream use.75 def _test(self):76 try:77 import haystack # noqa78 except (ImportError, ImproperlyConfigured) as e:79 return e80 def test_install(self):81 error = self._test()82 if isinstance(error, ImportError):83 return False84 def test_setup(self):85 error = self._test()86 if isinstance(error, ImproperlyConfigured):87 return False88class Openpyxl(Dependency):89 """Avocado comes with an export package for supporting various means of90 exporting data into different formats. One of those formats is the native91 Microsoft Excel .xlsx format. To support that, the openpyxl library is92 used.93 Install by doing `pip install openpyxl`.94 """95 name = 'openpyxl'96 def test_install(self):97 try:98 import openpyxl # noqa99 except ImportError:100 return False101class Guardian(Dependency):102 """This enables fine-grain control over who has permissions for various103 DataFields. Permissions can be defined at a user or group level.104 Install by doing `pip install django-guardian` and adding guardian to105 `INSTALLED_APPS`.106 """107 name = 'guardian'108 def test_install(self):109 try:110 import guardian # noqa111 except ImportError:112 return False113# Keep track of the officially supported apps and libraries used for various114# features.115OPTIONAL_DEPS = {116 'haystack': Haystack(),117 'openpyxl': Openpyxl(),118 'guardian': Guardian(),119}120def dep_supported(lib):121 return bool(OPTIONAL_DEPS[lib])122def raise_dep_error(lib):...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!