Skip to content

Commit

Permalink
docs: add java snippets to the examples in guides (#5638)
Browse files Browse the repository at this point in the history
  • Loading branch information
yury-s committed Mar 1, 2021
1 parent aeb2b2f commit 6c9e806
Show file tree
Hide file tree
Showing 22 changed files with 1,209 additions and 24 deletions.
64 changes: 61 additions & 3 deletions docs/src/assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@ text content of an element. These APIs can be used in your test assertions.

<!-- TOC -->


## Text content

```js
const content = await page.textContent('nav:first-child');
expect(content).toBe('home');
```

```java
String content = page.textContent("nav:first-child");
assertEquals("home", content);
```

```python async
content = await page.text_content("nav:first-child")
assert content == "home"
Expand All @@ -37,6 +41,11 @@ const text = await page.innerText('.selected');
expect(text).toBe('value');
```

```java
String text = page.innerText(".selected");
assertEquals("value", text);
```

```python async
text = await page.inner_text(".selected")
assert text == "value"
Expand All @@ -58,6 +67,11 @@ const alt = await page.getAttribute('input', 'alt');
expect(alt).toBe('Text');
```

```java
String alt = page.getAttribute("input", "alt");
assertEquals("Text", alt);
```

```python async
checked = await page.get_attribute("input", "alt")
assert alt == "Text"
Expand All @@ -75,6 +89,11 @@ const checked = await page.isChecked('input');
expect(checked).toBeTruthy();
```

```java
boolean checked = page.isChecked("input");
assertTrue(checked);
```

```python async
checked = await page.is_checked("input")
assert checked
Expand All @@ -96,6 +115,11 @@ const content = await page.$eval('nav:first-child', e => e.textContent);
expect(content).toBe('home');
```

```java
Object content = page.evalOnSelector("nav:first-child", "e => e.textContent");
assertEquals("home", content);
```

```python async
content = await page.eval_on_selector("nav:first-child", "e => e.textContent")
assert content == "home"
Expand All @@ -117,6 +141,11 @@ const html = await page.innerHTML('div.result');
expect(html).toBe('<p>Result</p>');
```

```java
String html = page.innerHTML("div.result");
assertEquals("<p>Result</p>", html);
```

```python async
html = await page.inner_html("div.result")
assert html == "<p>Result</p>"
Expand All @@ -138,6 +167,11 @@ const visible = await page.isVisible('input');
expect(visible).toBeTruthy();
```

```java
boolean visible = page.isVisible("input");
assertTrue(visible);
```

```python async
visible = await page.is_visible("input")
assert visible
Expand All @@ -156,7 +190,12 @@ assert visible

```js
const enabled = await page.isEnabled('input');
expect(visible).toBeTruthy();
expect(enabled).toBeTruthy();
```

```java
boolean enabled = page.isEnabled("input");
assertTrue(enabled);
```

```python async
Expand Down Expand Up @@ -198,6 +237,25 @@ const length = await page.$$eval('li.selected', (items) => items.length);
expect(length === 3).toBeTruthy();
```

```java
// Assert local storage value
Object userId = page.evaluate("() => window.localStorage.getItem('userId')");
assertNotNull(userId);

// Assert value for input element
page.waitForSelector("#search");
Object value = page.evalOnSelector("#search", "el => el.value");
assertEquals("query", value);

// Assert computed style
Object fontSize = page.evalOnSelector("div", "el => window.getComputedStyle(el).fontSize");
assertEquals("16px", fontSize);

// Assert list length
Object length = page.evalOnSelectorAll("li.selected", "items => items.length");
assertEquals(3, length);
```

```python async
# Assert local storage value
user_id = page.evaluate("() => window.localStorage.getItem('user_id')")
Expand Down Expand Up @@ -245,4 +303,4 @@ assert length == 3
- [`method: Frame.evalOnSelectorAll`]
- [`method: ElementHandle.evalOnSelector`]
- [`method: ElementHandle.evalOnSelectorAll`]
- [EvaluationArgument]
- [EvaluationArgument]
58 changes: 55 additions & 3 deletions docs/src/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ await page.click('text=Submit');
// Verify app is logged in
```

```java
Page page = context.newPage();
page.navigate("https://github.com/login");
// Interact with login form
page.click("text=Login");
page.fill("input[name='login']", USERNAME);
page.fill("input[name='password']", PASSWORD);
page.click("text=Submit");
// Verify app is logged in
```

```python async
page = await context.new_page()
await page.goto('https://github.com/login')
Expand Down Expand Up @@ -88,6 +99,16 @@ const storageState = JSON.parse(process.env.STORAGE);
const context = await browser.newContext({ storageState });
```

```java
// Save storage state and store as an env variable
String storage = context.storageState();
System.getenv().put("STORAGE", storage);

// Create a new context with the saved storage state
BrowserContext context = browser.newContext(
new Browser.NewContextOptions().withStorageState(storage));
```

```python async
import json
import os
Expand Down Expand Up @@ -150,6 +171,23 @@ await context.addInitScript(storage => {
}, sessionStorage);
```

```java
// Get session storage and store as env variable
String sessionStorage = (String) page.evaluate("() => JSON.stringify(sessionStorage");
System.getenv().put("SESSION_STORAGE", sessionStorage);

// Set session storage in a new context
String sessionStorage = System.getenv("SESSION_STORAGE");
context.addInitScript("(storage => {\n" +
" if (window.location.hostname === 'example.com') {\n" +
" const entries = JSON.parse(storage);\n" +
" Object.keys(entries).forEach(key => {\n" +
" window.sessionStorage.setItem(key, entries[key]);\n" +
" });\n" +
" }\n" +
"})(" + sessionStorage + ")");
```

```python async
import os
# Get session storage and store as env variable
Expand Down Expand Up @@ -199,8 +237,6 @@ manual intervention. Persistent authentication can be used to partially automate
MFA scenarios.

### Persistent authentication
Web browsers use a directory on disk to store user history, cookies, IndexedDB
and other local state. This disk location is called the [User data directory](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md).

Note that persistent authentication is not suited for CI environments since it
relies on a disk location. User data directories are specific to browser types
Expand All @@ -216,6 +252,22 @@ const context = await chromium.launchPersistentContext(userDataDir, { headless:
// Execute login steps manually in the browser window
```

```java
import com.microsoft.playwright.*;

public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
Path userDataDir = Paths.get("/path/to/directory");
BrowserContext context = chromium.launchPersistentContext(userDataDir,
new BrowserType.LaunchPersistentContextOptions().withHeadless(false));
// Execute login steps manually in the browser window
}
}
}
```

```python async
import asyncio
from playwright.async_api import async_playwright
Expand Down Expand Up @@ -246,4 +298,4 @@ with sync_playwright() as p:

### API reference
- [BrowserContext]
- [`method: BrowserType.launchPersistentContext`]
- [`method: BrowserType.launchPersistentContext`]
32 changes: 32 additions & 0 deletions docs/src/ci.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ Suggested configuration
});
```

```java
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.withArgs(Arrays.asList("--disable-dev-shm-usage")));
```

```python async
browser = await playwright.chromium.launch(
args=['--disable-dev-shm-usage']
Expand Down Expand Up @@ -233,6 +238,19 @@ const { chromium } = require('playwright');
const browser = await chromium.launch({ chromiumSandbox: false });
```
```java
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withChromiumSandbox(false));
}
}
}
```
```python async
browser = await playwright.chromium.launch(chromiumSandbox=False)
```
Expand Down Expand Up @@ -319,6 +337,20 @@ const { chromium } = require('playwright');
const browser = await chromium.launch({ headless: false });
```
```java
// Works across chromium, firefox and webkit
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withHeadless(false));
}
}
}
```
```python async
import asyncio
from playwright.async_api import async_playwright
Expand Down
21 changes: 21 additions & 0 deletions docs/src/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,27 @@ const { chromium } = require('playwright');
})();
```

```java
// FIXME
import com.microsoft.playwright.*;

public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
// Make sure to run headed.
Browser browser = chromium.launch(new BrowserType.LaunchOptions().withHeadless(false));
// Setup context however you like.
BrowserContext context = browser.newContext(/* pass any options */);
context.route("**/*", route -> route.resume());
// Pause the page, and start recording manually.
Page page = context.newPage();
page.pause();
}
}
}
```

```python async
import asyncio
from playwright.async_api import async_playwright
Expand Down
Loading

0 comments on commit 6c9e806

Please sign in to comment.