How to use buildTree method in Playwright Internal

Best JavaScript code snippet using playwright-internal

CQL.js

Source:CQL.js Github

copy

Full Screen

...199 }200 while (operatorStack.length > 0) {201 postfix.push(operatorStack.pop());202 }203 function buildTree() {204 var tok = postfix.pop();205 switch (tok.type) {206 case "LOGICAL":207 var rhs = buildTree(),208 lhs = buildTree();209 return new OpenLayers.Filter.Logical({210 filters: [lhs, rhs],211 type: logicals[tok.text.toUpperCase()]212 });213 case "NOT":214 var operand = buildTree();215 return new OpenLayers.Filter.Logical({216 filters: [operand],217 type: OpenLayers.Filter.Logical.NOT218 });219 case "BETWEEN":220 var min, max, property;221 postfix.pop(); // unneeded AND token here222 max = buildTree();223 min = buildTree();224 property = buildTree();225 return new OpenLayers.Filter.Comparison({226 property: property,227 lowerBoundary: min,228 upperBoundary: max,229 type: OpenLayers.Filter.Comparison.BETWEEN230 });231 case "COMPARISON":232 var value = buildTree(),233 property = buildTree();234 return new OpenLayers.Filter.Comparison({235 property: property,236 value: value,237 type: operators[tok.text.toUpperCase()]238 });239 case "IS_NULL":240 var property = buildTree();241 return new OpenLayers.Filter.Comparison({242 property: property,243 type: operators[tok.text.toUpperCase()]244 });245 case "VALUE":246 var match = tok.text.match(/^'(.*)'$/);247 if (match) {248 return match[1].replace(/''/g, "'");249 } else {250 return Number(tok.text);251 }252 case "SPATIAL":253 switch(tok.text.toUpperCase()) {254 case "BBOX":255 var maxy = buildTree(),256 maxx = buildTree(),257 miny = buildTree(),258 minx = buildTree(),259 prop = buildTree();260 return new OpenLayers.Filter.Spatial({261 type: OpenLayers.Filter.Spatial.BBOX,262 property: prop,263 value: OpenLayers.Bounds.fromArray(264 [minx, miny, maxx, maxy]265 )266 });267 case "INTERSECTS":268 var value = buildTree(),269 property = buildTree();270 return new OpenLayers.Filter.Spatial({271 type: OpenLayers.Filter.Spatial.INTERSECTS,272 property: property,273 value: value274 });275 case "WITHIN":276 var value = buildTree(),277 property = buildTree();278 return new OpenLayers.Filter.Spatial({279 type: OpenLayers.Filter.Spatial.WITHIN,280 property: property,281 value: value282 });283 case "CONTAINS":284 var value = buildTree(),285 property = buildTree();286 return new OpenLayers.Filter.Spatial({287 type: OpenLayers.Filter.Spatial.CONTAINS,288 property: property,289 value: value290 });291 case "DWITHIN":292 var distance = buildTree(),293 value = buildTree(),294 property = buildTree();295 return new OpenLayers.Filter.Spatial({296 type: OpenLayers.Filter.Spatial.DWITHIN,297 value: value,298 property: property,299 distance: Number(distance)300 });301 }302 case "GEOMETRY":303 return OpenLayers.Geometry.fromWKT(tok.text);304 default:305 return tok.text;306 }307 }308 var result = buildTree();309 if (postfix.length > 0) {310 var msg = "Remaining tokens after building AST: \n";311 for (var i = postfix.length - 1; i >= 0; i--) {312 msg += postfix[i].type + ": " + postfix[i].text + "\n";313 }314 throw new Error(msg);315 }316 return result;317 }318 return OpenLayers.Class(OpenLayers.Format, {319 /**320 * APIMethod: read321 * Generate a filter from a CQL string.322 * Parameters:...

Full Screen

Full Screen

shellbuildtrees.py

Source:shellbuildtrees.py Github

copy

Full Screen

1# Pylint doesn't play well with fixtures and dependency injection from pytest2# pylint: disable=redefined-outer-name3import os4import shutil5import pytest6from buildstream._testing import cli, cli_integration, Cli # pylint: disable=unused-import7from buildstream.exceptions import ErrorDomain8from buildstream._testing._utils.site import HAVE_SANDBOX9from tests.testutils import ArtifactShare10pytestmark = pytest.mark.integration11DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "project")12#13# Ensure that we didn't get a build tree if we didn't ask for one14#15@pytest.mark.datafiles(DATA_DIR)16@pytest.mark.skipif(not HAVE_SANDBOX, reason="Only available with a functioning sandbox")17def test_buildtree_unused(cli_integration, datafiles):18 # We can only test the non interacitve case19 # The non interactive case defaults to not using buildtrees20 # for `bst shell --build`21 project = str(datafiles)22 element_name = "build-shell/buildtree.bst"23 res = cli_integration.run(project=project, args=["--cache-buildtrees", "always", "build", element_name])24 res.assert_success()25 res = cli_integration.run(project=project, args=["shell", "--build", element_name, "--", "cat", "test"])26 res.assert_shell_error()27#28# Ensure we can use a buildtree from a successful build29#30@pytest.mark.datafiles(DATA_DIR)31@pytest.mark.skipif(not HAVE_SANDBOX, reason="Only available with a functioning sandbox")32def test_buildtree_from_success(cli_integration, datafiles):33 # Test that if we ask for a build tree it is there.34 project = str(datafiles)35 element_name = "build-shell/buildtree.bst"36 res = cli_integration.run(project=project, args=["--cache-buildtrees", "always", "build", element_name])37 res.assert_success()38 res = cli_integration.run(39 project=project, args=["shell", "--build", "--use-buildtree", element_name, "--", "cat", "test"]40 )41 res.assert_success()42 assert "Hi" in res.output43#44# Ensure we can use a buildtree from a failed build45#46@pytest.mark.datafiles(DATA_DIR)47@pytest.mark.skipif(not HAVE_SANDBOX, reason="Only available with a functioning sandbox")48def test_buildtree_from_failure(cli_integration, datafiles):49 # Test that we can use a build tree after a failure50 project = str(datafiles)51 element_name = "build-shell/buildtree-fail.bst"52 res = cli_integration.run(project=project, args=["build", element_name])53 res.assert_main_error(ErrorDomain.STREAM, None)54 # Assert that file has expected contents55 res = cli_integration.run(56 project=project, args=["shell", "--build", element_name, "--use-buildtree", "--", "cat", "test"]57 )58 res.assert_success()59 assert "WARNING using a buildtree from a failed build" in res.stderr60 assert "Hi" in res.output61###########################################################################62# Custom fixture ahead #63###########################################################################64#65# There are a lot of scenarios to test with launching shells with various states66# of local cache, which all require that artifacts be built in an artifact share.67#68# We want to use @pytest.mark.parametrize() here so that we can more coherently test69# specific scenarios, but testing each of these in a separate test is very expensive.70#71# For this reason, we use some module scope fixtures which will prepare the72# ArtifactShare() object by building and pushing to it, and the same ArtifactShare()73# object is shared across all tests which need the ArtifactShare() to be in that74# given state.75#76# This means we only need to download (fetch) the external alpine runtime and77# push it to our internal ArtifactShare() once, but we can reuse it for many78# parametrized tests.79#80# It is important that none of the tests using these fixtures access the81# module scope ArtifactShare() instances with "push" access, as tests82# should not be modifying the state of the shared data.83#84###########################################################################85# create_built_artifact_share()86#87# A helper function to create an ArtifactShare object with artifacts88# prebuilt, this can be shared across multiple tests which access89# the artifact share in a read-only fashion.90#91# Args:92# tmpdir (str): The temp directory to be used93# cache_buildtrees (bool): Whether to cache buildtrees when building94# integration_cache (IntegrationCache): The session wide integration cache so that we95# can reuse the sources from previous runs96#97def create_built_artifact_share(tmpdir, cache_buildtrees, integration_cache):98 element_name = "build-shell/buildtree.bst"99 # Replicate datafiles behavior and do work entirely in the temp directory100 project = os.path.join(tmpdir, "project")101 shutil.copytree(DATA_DIR, project)102 # Create the share to be hosted from this temp directory103 share = ArtifactShare(os.path.join(tmpdir, "artifactcache"))104 # Create a Cli instance to build and populate the share105 cli = Cli(os.path.join(tmpdir, "cache"))106 cli.configure(107 {"artifacts": {"servers": [{"url": share.repo, "push": True}]}, "sourcedir": integration_cache.sources}108 )109 # Optionally cache build trees110 args = []111 if cache_buildtrees:112 args += ["--cache-buildtrees", "always"]113 args += ["build", element_name]114 # Build115 result = cli.run(project=project, args=args)116 result.assert_success()117 # Assert that the artifact is indeed in the share118 assert cli.get_element_state(project, element_name) == "cached"119 artifact_name = cli.get_artifact_name(project, "test", element_name)120 assert share.get_artifact(artifact_name)121 return share122# share_with_buildtrees()123#124# A module scope fixture which prepares an ArtifactShare() instance125# which will have all dependencies of "build-shell/buildtree.bst" built and126# cached with buildtrees also cached.127#128@pytest.fixture(scope="module")129def share_with_buildtrees(tmp_path_factory, integration_cache):130 # Get a temporary directory for this module scope fixture131 tmpdir = tmp_path_factory.mktemp("artifact_share_with_buildtrees")132 # Create our ArtifactShare instance which will persist for the duration of133 # the class scope fixture.134 share = create_built_artifact_share(tmpdir, True, integration_cache)135 try:136 yield share137 finally:138 share.close()139# share_without_buildtrees()140#141# A module scope fixture which prepares an ArtifactShare() instance142# which will have all dependencies of "build-shell/buildtree.bst" built143# but without caching any buildtrees.144#145@pytest.fixture(scope="module")146def share_without_buildtrees(tmp_path_factory, integration_cache):147 # Get a temporary directory for this module scope fixture148 tmpdir = tmp_path_factory.mktemp("artifact_share_without_buildtrees")149 # Create our ArtifactShare instance which will persist for the duration of150 # the class scope fixture.151 share = create_built_artifact_share(tmpdir, False, integration_cache)152 try:153 yield share154 finally:155 share.close()156# maybe_pull_deps()157#158# Convenience function for optionally pulling element dependencies159# in the following parametrized tests.160#161# Args:162# cli (Cli): The Cli object163# project (str): The project path164# element_name (str): The element name165# pull_deps (str): The argument for `--deps`, or None166# pull_buildtree (bool): Whether to also pull buildtrees167#168def maybe_pull_deps(cli, project, element_name, pull_deps, pull_buildtree):169 # Optionally pull the buildtree along with `bst artifact pull`170 if pull_deps:171 args = []172 if pull_buildtree:173 args += ["--pull-buildtrees"]174 args += ["artifact", "pull", "--deps", pull_deps, element_name]175 # Pull from cache176 result = cli.run(project=project, args=args)177 result.assert_success()178#179# Test behavior of launching a shell and requesting to use a buildtree, with180# various states of local cache (ranging from nothing cached to everything cached)181#182@pytest.mark.datafiles(DATA_DIR)183@pytest.mark.skipif(not HAVE_SANDBOX, reason="Only available with a functioning sandbox")184@pytest.mark.parametrize(185 "pull_deps,pull_buildtree,expect_error",186 [187 # Don't pull at all188 (None, False, "missing-buildtree-artifact-not-cached"),189 # Pull only dependencies190 ("build", False, "missing-buildtree-artifact-not-cached"),191 # Pull all elements including the shell element, but without the buildtree192 ("all", False, "missing-buildtree-artifact-buildtree-not-cached"),193 # Pull all elements including the shell element, and pull buildtrees194 ("all", True, None),195 # Pull only the artifact, but without the buildtree196 ("none", False, "missing-buildtree-artifact-buildtree-not-cached"),197 # Pull only the artifact with its buildtree198 ("none", True, None),199 ],200 ids=[201 "no-pull",202 "pull-only-deps",203 "pull-without-buildtree",204 "pull-with-buildtree",205 "pull-target-without-buildtree",206 "pull-target-with-buildtree",207 ],208)209def test_shell_use_cached_buildtree(share_with_buildtrees, datafiles, cli, pull_deps, pull_buildtree, expect_error):210 project = str(datafiles)211 element_name = "build-shell/buildtree.bst"212 cli.configure({"artifacts": {"servers": [{"url": share_with_buildtrees.repo}]}})213 # Optionally pull the buildtree along with `bst artifact pull`214 maybe_pull_deps(cli, project, element_name, pull_deps, pull_buildtree)215 # Disable access to the artifact server after pulling, so that `bst shell` cannot automatically216 # pull the missing bits, this should be equivalent to the missing bits being missing in a217 # remote server218 cli.configure({"artifacts": {}})219 # Run the shell without asking it to pull any buildtree, just asking to use a buildtree220 result = cli.run(project=project, args=["shell", "--build", element_name, "--use-buildtree", "--", "cat", "test"])221 if expect_error:222 result.assert_main_error(ErrorDomain.APP, expect_error)223 else:224 result.assert_success()225 assert "Hi" in result.output226#227# Test behavior of launching a shell and requesting to use a buildtree, while allowing228# BuildStream to download any missing bits from the artifact server on the fly (which229# it will do by default) again with various states of local cache (ranging from nothing230# cached to everything cached)231#232@pytest.mark.datafiles(DATA_DIR)233@pytest.mark.skipif(not HAVE_SANDBOX, reason="Only available with a functioning sandbox")234@pytest.mark.parametrize(235 "pull_deps,pull_buildtree",236 [237 # Don't pull at all238 (None, False),239 # Pull only dependencies240 ("build", False),241 # Pull all elements including the shell element, but without the buildtree242 ("all", False),243 # Pull all elements including the shell element, and pull buildtrees244 ("all", True),245 ],246 ids=["no-pull", "pull-only-deps", "pull-without-buildtree", "pull-with-buildtree"],247)248def test_shell_pull_cached_buildtree(share_with_buildtrees, datafiles, cli, pull_deps, pull_buildtree):249 project = str(datafiles)250 element_name = "build-shell/buildtree.bst"251 cli.configure({"artifacts": {"servers": [{"url": share_with_buildtrees.repo}]}})252 # Optionally pull the buildtree along with `bst artifact pull`253 maybe_pull_deps(cli, project, element_name, pull_deps, pull_buildtree)254 # Run the shell and request that required artifacts and buildtrees should be pulled255 result = cli.run(256 project=project,257 args=[258 "--pull-buildtrees",259 "shell",260 "--build",261 element_name,262 "--use-buildtree",263 "--",264 "cat",265 "test",266 ],267 )268 # In this case, we should succeed every time, regardless of what was269 # originally available in the local cache.270 #271 result.assert_success()272 assert "Hi" in result.output273#274# Test behavior of shelling into a buildtree by its artifact name275#276@pytest.mark.datafiles(DATA_DIR)277@pytest.mark.skipif(not HAVE_SANDBOX, reason="Only available with a functioning sandbox")278def test_shell_pull_artifact_cached_buildtree(share_with_buildtrees, datafiles, cli):279 project = str(datafiles)280 artifact_name = "test/build-shell-buildtree/4a47c98a10df39e65e99d471f96edc5b58d4ea5b9b1f221d0be832a8124b8099"281 cli.configure({"artifacts": {"servers": [{"url": share_with_buildtrees.repo}]}})282 # Run the shell and request that required artifacts and buildtrees should be pulled283 result = cli.run(284 project=project,285 args=[286 "--pull-buildtrees",287 "shell",288 "--build",289 "--use-buildtree",290 artifact_name,291 "--",292 "cat",293 # We don't preserve the working directory in artifacts, so we will be executing at /294 "/buildstream/test/build-shell/buildtree.bst/test",295 ],296 )297 # In this case, we should succeed every time, regardless of what was298 # originally available in the local cache.299 #300 result.assert_success()301 assert "Hi" in result.output302#303# Test behavior of launching a shell and requesting to use a buildtree.304#305# In this case we download everything we need first, but the buildtree was never cached at build time306#307@pytest.mark.datafiles(DATA_DIR)308@pytest.mark.skipif(not HAVE_SANDBOX, reason="Only available with a functioning sandbox")309def test_shell_use_uncached_buildtree(share_without_buildtrees, datafiles, cli):310 project = str(datafiles)311 element_name = "build-shell/buildtree.bst"312 cli.configure({"artifacts": {"servers": [{"url": share_without_buildtrees.repo}]}})313 # Pull everything we would need314 maybe_pull_deps(cli, project, element_name, "all", True)315 # Run the shell without asking it to pull any buildtree, just asking to use a buildtree316 result = cli.run(project=project, args=["shell", "--build", element_name, "--use-buildtree", "--", "cat", "test"])317 # Sorry, a buildtree was never cached for this element318 result.assert_main_error(ErrorDomain.APP, "missing-buildtree-artifact-created-without-buildtree")319@pytest.mark.datafiles(DATA_DIR)320@pytest.mark.skipif(not HAVE_SANDBOX, reason="Only available with a functioning sandbox")321def test_shell_script_element(datafiles, cli_integration):322 project = str(datafiles)323 element_name = "build-shell/script.bst"324 result = cli_integration.run(project=project, args=["--cache-buildtrees", "always", "build", element_name])325 result.assert_success()326 # Run the shell and use the cached buildtree on this script element327 result = cli_integration.run(328 project=project, args=["shell", "--build", element_name, "--use-buildtree", "--", "cat", "/test"]329 )330 result.assert_success()331 assert "Hi" in result.output332@pytest.mark.datafiles(DATA_DIR)333@pytest.mark.skipif(not HAVE_SANDBOX, reason="Only available with a functioning sandbox")334@pytest.mark.parametrize(335 "element_name,expect_success",336 [337 # Build shell into a compose element which succeeded338 ("build-shell/compose-success.bst", True),339 # Build shell into a compose element with failed integration commands340 ("build-shell/compose-fail.bst", False),341 ],342 ids=["integration-success", "integration-fail"],343)344def test_shell_compose_element(datafiles, cli_integration, element_name, expect_success):345 project = str(datafiles)346 # Build the element so it's in the local cache, ensure caching of buildtrees at build time347 result = cli_integration.run(project=project, args=["--cache-buildtrees", "always", "build", element_name])348 if expect_success:349 result.assert_success()350 else:351 result.assert_main_error(ErrorDomain.STREAM, None)352 # Ensure that the shell works regardless of success expectations353 #354 result = cli_integration.run(355 project=project, args=["shell", "--build", element_name, "--use-buildtree", "--", "echo", "Hi"]356 )357 result.assert_success()358 assert "Hi" in result.output359 # Check the file created with integration commands360 #361 result = cli_integration.run(362 project=project,363 args=["shell", "--build", element_name, "--use-buildtree", "--", "cat", "/integration-success"],364 )365 if expect_success:366 result.assert_success()367 assert "Hi" in result.output368 else:369 # Here the exit code is determined by `cat`, and will be non-zero.370 #371 # We cannot use result.assert_main_error() because that explicitly expects -1...

Full Screen

Full Screen

parser.js

Source:parser.js Github

copy

Full Screen

...193 }194 while (operatorStack.length > 0) {195 postfix.push(operatorStack.pop());196 }197 function buildTree() {198 let tok = postfix.pop();199 switch (tok.type) {200 case "LOGICAL":201 let rhs = buildTree();202 let lhs = buildTree();203 return ({204 filters: [lhs, rhs],205 type: logical[tok.text.toUpperCase()]206 });207 case "NOT":208 let operand = buildTree();209 return ({210 filters: [operand],211 type: logical.NOT212 });213 case "BETWEEN": {214 postfix.pop(); // unneeded AND token here215 let max = buildTree();216 let min = buildTree();217 const property = buildTree();218 return ({219 property,220 lowerBoundary: min,221 upperBoundary: max,222 type: operators.BETWEEN223 });224 }225 case "COMPARISON": {226 let value = buildTree();227 const property = buildTree();228 return ({229 property,230 value: value,231 type: operators[tok.text.toUpperCase()]232 });233 }234 case "IS_NULL": {235 const property = buildTree();236 return ({237 property,238 type: operators[tok.text.toUpperCase()]239 });240 }241 case "VALUE":242 let match = tok.text.match(/^'(.*)'$/);243 if (match) {244 return match[1].replace(/''/g, "'");245 }246 return Number(tok.text);247 case "SPATIAL":248 switch (tok.text.toUpperCase()) {249 case "BBOX": {250 let maxy = buildTree();251 let maxx = buildTree();252 let miny = buildTree();253 let minx = buildTree();254 let property = buildTree();255 return ({256 type: spatialOperators.BBOX,257 property,258 value: [minx, miny, maxx, maxy] // TODO: evaluate this special case259 });260 }261 case "INTERSECTS": {262 const value = buildTree();263 const property = buildTree();264 return ({265 type: spatialOperators.INTERSECTS,266 property,267 value268 });269 }270 case "WITHIN": {271 let value = buildTree();272 let property = buildTree();273 return ({274 type: spatialOperators.WITHIN,275 property,276 value277 });278 }279 case "CONTAINS": {280 let value = buildTree();281 const property = buildTree();282 return ({283 type: spatialOperators.CONTAINS,284 property,285 value286 });287 }288 case "DWITHIN": {289 let distance = buildTree();290 let value = buildTree();291 const property = buildTree();292 return ({293 type: spatialOperators.DWITHIN,294 value,295 property,296 distance: Number(distance)297 });298 }299 default:300 return null;301 }302 case "GEOMETRY":303 return fromWKT(tok.text);304 default:305 return tok.text;306 }307 }308 let result = buildTree();309 if (postfix.length > 0) {310 let msg = "Remaining tokens after building AST: \n";311 for (let i = postfix.length - 1; i >= 0; i--) {312 msg += postfix[i].type + ": " + postfix[i].text + "\n";313 }314 throw new Error(msg);315 }316 return result;317};318module.exports = {319 /**320 * Parse a CQL filter. returns an object representation of the filter.321 * For the moment this parser doesn't support WKT parsing.322 * Example:...

Full Screen

Full Screen

tree_building_test.py

Source:tree_building_test.py Github

copy

Full Screen

1import unittest2from tree_building import Record, BuildTree3class TestBuildingTest(unittest.TestCase):4 """5 Record(record_id, parent_id): records given to be processed6 Node(node_id): Node in tree7 BuildTree(records): records as argument and returns tree8 BuildTree should raise ValueError if given records are invalid9 """10 def test_empty_list_input(self):11 records = []12 root = BuildTree(records)13 self.assertIsNone(root)14 def test_one_node(self):15 records = [16 Record(0, 0)17 ]18 root = BuildTree(records)19 self.assert_node_is_leaf(root, node_id=0)20 def test_three_nodes_in_order(self):21 records = [22 Record(0, 0),23 Record(1, 0),24 Record(2, 0)25 ]26 root = BuildTree(records)27 self.assert_node_is_branch(root, node_id=0, children_count=2)28 self.assert_node_is_leaf(root.children[0], node_id=1)29 self.assert_node_is_leaf(root.children[1], node_id=2)30 def test_three_nodes_in_reverse_order(self):31 records = [32 Record(2, 0),33 Record(1, 0),34 Record(0, 0)35 ]36 root = BuildTree(records)37 self.assert_node_is_branch(root, node_id=0, children_count=2)38 self.assert_node_is_leaf(root.children[0], node_id=1)39 self.assert_node_is_leaf(root.children[1], node_id=2)40 def test_more_than_two_children(self):41 records = [42 Record(0, 0),43 Record(1, 0),44 Record(2, 0),45 Record(3, 0)46 ]47 root = BuildTree(records)48 self.assert_node_is_branch(root, node_id=0, children_count=3)49 self.assert_node_is_leaf(root.children[0], node_id=1)50 self.assert_node_is_leaf(root.children[1], node_id=2)51 self.assert_node_is_leaf(root.children[2], node_id=3)52 def test_binary_tree(self):53 records = [54 Record(6, 2),55 Record(0, 0),56 Record(3, 1),57 Record(2, 0),58 Record(4, 1),59 Record(5, 2),60 Record(1, 0)61 ]62 root = BuildTree(records)63 self.assert_node_is_branch(root, 0, 2)64 self.assert_node_is_branch(root.children[0], 1, 2)65 self.assert_node_is_branch(root.children[1], 2, 2)66 self.assert_node_is_leaf(root.children[0].children[0], 3)67 self.assert_node_is_leaf(root.children[0].children[1], 4)68 self.assert_node_is_leaf(root.children[1].children[0], 5)69 self.assert_node_is_leaf(root.children[1].children[1], 6)70 def test_unbalanced_tree(self):71 records = [72 Record(0, 0),73 Record(1, 0),74 Record(2, 0),75 Record(3, 1),76 Record(4, 1),77 Record(5, 1),78 Record(6, 2),79 ]80 root = BuildTree(records)81 self.assert_node_is_branch(root, 0, 2)82 self.assert_node_is_branch(root.children[0], 1, 3)83 self.assert_node_is_branch(root.children[1], 2, 1)84 self.assert_node_is_leaf(root.children[0].children[0], 3)85 self.assert_node_is_leaf(root.children[0].children[1], 4)86 self.assert_node_is_leaf(root.children[0].children[2], 5)87 self.assert_node_is_leaf(root.children[1].children[0], 6)88 def test_root_node_has_parent(self):89 records = [90 Record(0, 1),91 Record(1, 0)92 ]93 # Root parent_id should be equal to record_id(0)94 with self.assertRaisesWithMessage(ValueError):95 BuildTree(records)96 def test_no_root_node(self):97 records = [98 Record(1, 0),99 Record(2, 0)100 ]101 # Record with record_id 0 (root) is missing102 with self.assertRaisesWithMessage(ValueError):103 BuildTree(records)104 def test_non_continuous(self):105 records = [106 Record(2, 0),107 Record(4, 2),108 Record(1, 0),109 Record(0, 0)110 ]111 # Record with record_id 3 is missing112 with self.assertRaisesWithMessage(ValueError):113 BuildTree(records)114 def test_cycle_directly(self):115 records = [116 Record(5, 2),117 Record(3, 2),118 Record(2, 2),119 Record(4, 1),120 Record(1, 0),121 Record(0, 0),122 Record(6, 3)123 ]124 # Cycle caused by Record 2 with parent_id pointing to itself125 with self.assertRaisesWithMessage(ValueError):126 BuildTree(records)127 def test_cycle_indirectly(self):128 records = [129 Record(5, 2),130 Record(3, 2),131 Record(2, 6),132 Record(4, 1),133 Record(1, 0),134 Record(0, 0),135 Record(6, 3)136 ]137 # Cycle caused by Record 2 with parent_id(6) greater than record_id(2)138 with self.assertRaisesWithMessage(ValueError):139 BuildTree(records)140 def test_higher_id_parent_of_lower_id(self):141 records = [142 Record(0, 0),143 Record(2, 0),144 Record(1, 2)145 ]146 # Record 1 have parent_id(2) greater than record_id(1)147 with self.assertRaisesWithMessage(ValueError):148 BuildTree(records)149 def assert_node_is_branch(self, node, node_id, children_count):150 self.assertEqual(node.node_id, node_id)151 self.assertNotEqual(len(node.children), 0)152 self.assertEqual(len(node.children), children_count)153 def assert_node_is_leaf(self, node, node_id):154 self.assertEqual(node.node_id, node_id)155 self.assertEqual(len(node.children), 0)156 # Utility functions157 def setUp(self):158 try:159 self.assertRaisesRegex160 except AttributeError:161 self.assertRaisesRegex = self.assertRaisesRegexp162 def assertRaisesWithMessage(self, exception):163 return self.assertRaisesRegex(exception, r".+")164if __name__ == '__main__':...

Full Screen

Full Screen

config.js

Source:config.js Github

copy

Full Screen

1/*jslint regexp: true, node: true, nomen: true */2var Config = {3 manifestUrlTemplate: "http://build.webos-ports.org/luneos-%%BUILDTREE%%/manifest.json",4 versionFile: "/etc/luneos-release",5 //regexp to parse webos-release file. Will return:6 //${BUILD_DISTRIB_ID} release ${DISTRO_VERSION}-${BUILD_TREE}-${WEBOS_DISTRO_BUILD_ID} (${WEBOS_DISTRO_RELEASE_CODENAME})7 //where ${WEBOS_DISTRO_BUILD_ID} is ${PLATFORMVERSION}-${BUILD}8 //and BUILD_TREE is one of stable, testing, unstable.9 parseWholeStringRegExp: /([0-9\._\-A-Za-z]+) release ([0-9\.]+)-([A-Za-z\/\-0-9]+)-([0-9]+)-([0-9]+) \(([0-9a-zA-Z_\-\.]+)\)/,10 parseWholeStringIndex: 4,11 parseWholeStringBuildTreeIndex: 3,12 parseWholeStringBuildIndex: 5,13 parseWholeStringCodenameIndex: 6,14 parseOnlyPlatformVersionRegExp: /.*?-([0-9]+)-.*?/,15 //download image:16 downloadPath: "/userdata/luneos-data/",17 downloadFilename: "system-update.zip",18 deviceImagesUrlTemplate: "http://build.webos-ports.org/luneos-%%BUILDTREE%%/device-images.json", //a json that contains the urls of the images to download19 //install update20 rebootToUpdateModeCommand: {cmd: "script", args: ["-q", "-c", "/usr/palm/services/org.webosports.service.update/start-update.sh", "/dev/null"]},21 //misc stuff22 checkUpdateResultsFile: "/tmp/checkUpdateResults.json",23 getDeviceNameCommand: {cmd: "nyx-cmd", args: ["DeviceInfo", "query", "--format=json"] },24 _buildUrl: function (template, buildtree) {25 "use strict";26 if (!buildtree) {27 buildtree = "stable";28 }29 return template.replace("%%BUILDTREE%%", buildtree);30 },31 getManifestUrl: function (buildtree) {32 "use strict";33 return Config._buildUrl(Config.manifestUrlTemplate, buildtree);34 },35 getDeviceImagesUrl: function (buildtree) {36 "use strict";37 return Config._buildUrl(Config.deviceImagesUrlTemplate, buildtree);38 }39};...

Full Screen

Full Screen

sameTree.test.js

Source:sameTree.test.js Github

copy

Full Screen

...26 */27 describe('Recursive version', function () {28 test('should check if they are the same or not', function () {29 expect(isSameTreeRecursive(null, null)).toEqual(true)30 expect(isSameTreeRecursive(null, buildTree([1]))).toEqual(false)31 expect(isSameTreeRecursive(buildTree([1]), null)).toEqual(false)32 expect(isSameTreeRecursive(buildTree([1, 2, 4]), buildTree([1, 2, 4]))).toEqual(true)33 expect(isSameTreeRecursive(buildTree([1, 2, 4]), buildTree([1, 2, 5]))).toEqual(false)34 expect(isSameTreeRecursive(buildTree([1, 2, 4]), buildTree([1, 2, null, 4, null]))).toEqual(35 false36 )37 })38 })39 describe('Recursive version', function () {40 test('should check if they are the same or not', function () {41 expect(isSameTreeIterative(null, null)).toEqual(true)42 expect(isSameTreeIterative(null, buildTree([1]))).toEqual(false)43 expect(isSameTreeIterative(buildTree([1]), null)).toEqual(false)44 expect(isSameTreeIterative(buildTree([1, 2, 4]), buildTree([1, 2, 4]))).toEqual(true)45 expect(isSameTreeIterative(buildTree([1, 2, 4]), buildTree([1, 2, 5]))).toEqual(false)46 expect(isSameTreeIterative(buildTree([1, 2, 4]), buildTree([1, 2, null, 4, null]))).toEqual(47 false48 )49 })50 })...

Full Screen

Full Screen

preorder.py

Source:preorder.py Github

copy

Full Screen

...4 self.val = val5 self.left = None6 self.right = None7 8 def buildTree(self,data):9 if data == self.val:10 return11 12 # add in left13 if data < self.val:14 if self.left:15 self.left.buildTree(data)16 else:17 self.left = BuildTree(data)18 19 # add in right20 else:21 if self.right:22 self.right.buildTree(data)23 else:24 self.right = BuildTree(data)25 def preorder(self,root):26 if root:27 print(root.val)28 self.preorder(root.left)29 self.preorder(root.right)30s = BuildTree(10)31s.buildTree(5)32s.buildTree(15)33s.buildTree(3)34s.buildTree(7)35s.buildTree(18)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildTree } = require('playwright/lib/utils/dom');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const html = await page.content();8 const dom = buildTree(html);9 console.log(dom);10 await browser.close();11})();12### `buildTree(html, options)`

Full Screen

Using AI Code Generation

copy

Full Screen

1import { buildTree } from "@playwright/test";2import { test } from "@playwright/test";3import { expect } from "@playwright/test";4test("test", async ({ page }) => {5 const tree = await buildTree(page);6 expect(tree).toMatchSnapshot();7});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildTree } = require('@playwright/test/lib/utils/buildTree');2const { test } = require('@playwright/test');3test.describe('test', () => {4 test('test', async ({ page }) => {5 const tree = await buildTree(page, 'body');6 console.log(tree);7 });8});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { buildTree } = require('playwright/lib/server/inspector/buildTree');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('text=Images');8 const tree = await buildTree(page);9 console.log(JSON.stringify(tree, null, 2));10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildTree } = require('@playwright/test/lib/utils/locator');2const { test, expect } = require('@playwright/test');3test('buildTree', async ({ page }) => {4 await page.setContent('<html><body><div>hello</div></body></html>');5 const div = await page.$('div');6 const tree = buildTree(div);7 expect(tree).toEqual({8 attributes: {},9 {10 attributes: {},11 },12 });13});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildTree } = require('@playwright/test/lib/utils/locator');2const { chromium } = require('playwright');3const { test, expect } = require('@playwright/test');4test('test', async ({ page }) => {5 const locator = buildTree(page, 'header >> text=Get started');6 const element = await locator.elementHandle();7 await element.click();8 await page.screenshot({ path: `example.png` });9});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildTree } = require('@playwright/test/build/utils/buildTree');2const tree = buildTree({3 import { test } from '@playwright/test';4 test('test', async ({ page }) => {5 });6});7const { runTest } = require('@playwright/test/build/runner');8const result = await runTest(tree.suites[0].specs[0], {9});10const { runCLI } = require('@playwright/test/build/cli/parseArgs');11const result = await runCLI(['--help']);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildTree } = require('@playwright/test/lib/utils/traceModel');2const trace = require('./trace.json');3const tree = buildTree(trace);4console.log(JSON.stringify(tree, null, 2));5const { buildTree } = require('@playwright/test/lib/utils/traceModel');6const trace = require('./trace.json');7const tree = buildTree(trace);8console.log(JSON.stringify(tree, null, 2));9const { buildTree } = require('@playwright/test/lib/utils/traceModel');10const trace = require('./trace.json');11const tree = buildTree(trace, {12 filter: (event) => {13 return event.name === 'ResourceSendRequest';14 },15});16console.log(JSON.stringify(tree, null, 2));17const { buildTree } = require('@playwright/test/lib/utils/traceModel');18const trace = require('./trace.json');19const tree = buildTree(trace, {20 filter: (event) => {21 return event.name === 'ResourceSendRequest';22 },23 transform: (event) => {24 return {25 };26 },27});28console.log(JSON.stringify(tree, null, 2));29const { buildTree } = require('@playwright/test/lib/utils/traceModel');30const trace = require('./trace.json');31const tree = buildTree(trace, {32 filter: (event) => {33 return event.name === 'ResourceSendRequest';34 },35 transform: (event, context) => {36 return {37 };38 },39});40console.log(JSON.stringify(tree, null, 2));41const { buildTree } = require('@playwright/test/lib/utils/traceModel');42const trace = require('./trace.json');43const tree = buildTree(trace, {44 filter: (event) => {45 return event.name === 'ResourceSendRequest';46 },47 transform: (event, context, parent) => {48 return {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildTree } = require('@playwright/test/lib/utils/inspectorHelper');2const tree = buildTree({3 {4 { title: 'Step 1.1' },5 { title: 'Step 1.2' },6 },7 { title: 'Step 2' },8});9console.log(tree);10[Apache 2.0](LICENSE)

Full Screen

Using AI Code Generation

copy

Full Screen

1const { buildTree } = require('@playwright/test');2const tree = buildTree();3console.log(tree);4interface Test {5 id: string;6 title: string;7 location: string;8 file: string;9 line: number;10 column: number;11 fn: Function;12 timeout: number;13 annotations: Annotation[];14 results: TestResult[];15 retries: number;16 expectedStatus: 'passed' | 'failed' | 'skipped';17 expectedIssues: string[];18 expectedSnapshots: string[];19 slowMo: number;20 repeatEachIndex: number;21 repeatEachIterations: number;22 repeatEachSeparate: boolean;23 isFocused: boolean;24 isFlaky: boolean;25 isExpectedToFail: boolean;26 isExpectedToPass: boolean;27 isSkipped: boolean;28 isSlow: boolean;29 isStable: boolean;30 isTodo: boolean;31 isUnstable: boolean;32 isWorker: boolean;33 isExternal: boolean;34 isFailing: boolean;35 isPassing: boolean;36 isPending: boolean;37 isRetried: boolean;38 isTerminal: boolean;39 isFailed: boolean;40 isFinished: boolean;41 isRunning: boolean;42 isScheduled: boolean;43 isDone: boolean;44 isStarted: boolean;45 isStopped: boolean;46 isTimedOut: boolean;47 isSkipped: boolean;48 isExpected: boolean;49 isUnexpected: boolean;50 isFlaky: boolean;51 isStable: boolean;52 isUnstable: boolean;53 isSlow: boolean;54 isFast: boolean;55 isExpectedToFail: boolean;56 isExpectedToPass: boolean;57 isTodo: boolean;58 isWorker: boolean;59 isExternal: boolean;60 isFailing: boolean;61 isPassing: boolean;62 isPending: boolean;63 isRetried: boolean;64 isTerminal: boolean;65 isFailed: boolean;66 isFinished: boolean;67 isRunning: boolean;68 isScheduled: boolean;

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal 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