text:
---
title: "Browser manipulation"
weight: 3
---

{{% notice info %}}
 页面需要从英语翻译为简体中文。
您熟悉英语与简体中文吗?帮助我们翻译它,通过 pull requests 给我们!
{{% /notice %}}

## Ruby

Ruby is not installed by default on Windows. Download the latest
[version](//rubyinstaller.org/downloads) and run the installer. You can
leave all settings at default values, except at the
_Installation Destination and Optional Tasks_ screen check
_Add Ruby executables to your PATH_ checkbox. To drive any browser, you have
to install `selenium-webdriver` Ruby gem. To install it, open command prompt
and type this:

```shell
gem install selenium-webdriver
```

Or, if you use [Bundler](//bundler.io), add this line to your application's
Gemfile:

```ruby
gem "selenium-webdriver"
```

And then execute the following command in prompt:

```shell
bundle install
```

## Internet Explorer

Internet Explorer is installed by default on Windows, so no installation is
needed. To drive Internet Explorer on Windows, you have to download the latest
[Internet Explorer Driver](//www.seleniumhq.org/download/) and put the file
into a folder that is in `PATH`. To find out which directories are in `PATH`,
type `echo %PATH%` in command prompt.

```bat
$ echo %PATH%
C:\Ruby200\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem
```

`C:\Ruby200\bin` looks like a good place. Unzip `IEDriverServer` file and
move `IEDriverServer.exe` there.

This should open a new Internet Explorer window:

```ruby
require "selenium-webdriver"
driver = Selenium::WebDriver.for :internet_explorer
```

## Browser navigation

### Navigate to

The first thing you will want to do after launching a browser is to
open your website. This can be achieved in a single line:

{{}}
  {{}}
//Convenient
driver.get("https://www.seleniumhq.org");

//Longer way
driver.navigate().to("https://seleniumhq.github.io/docs/");
  {{}}
  {{}}
driver.get("https://www.seleniumhq.org")
  {{}}
  {{}}
driver.Navigate().GoToUrl(@"http://google.com");
  {{}}
  {{}}
# Convenient way
driver.get 'https://www.seleniumhq.org'

# Longer Way
driver.navigate.to 'https://www.seleniumhq.org'
  {{}}
  {{}}
await driver.get('https://seleniumhq.github.io/docs/');
  {{}}
  {{}}
//Convenient
driver.get("https://www.seleniumhq.org")

//Longer way
driver.navigate().to("https://seleniumhq.github.io/docs/")
  {{}}
{{}}

### Get current URL

You can read the current URL from the browser's address bar using:

{{}}
  {{}}driver.getCurrentUrl();{{}}
  {{}}driver.current_url{{}}
  {{}}driver.Url;{{}}
  {{}}driver.current_url{{}}
  {{}}await driver.getCurrentUrl();{{}}
  {{}}driver.getCurrentUrl();{{}}
{{}}

### Back

Pressing the browser's back button:

{{}}
  {{}}driver.navigate().back();{{}}
  {{}}driver.back(){{}}
  {{}}driver.Navigate().Back();{{}}
  {{}}driver.navigate.back{{}}
  {{}}await driver.navigate().back();{{}}
  {{}}driver.navigate().back() {{}}
{{}}

### Forward
Pressing the browser's forward button:

{{}}
  {{}}driver.navigate().forward();{{}}
  {{}}driver.forward(){{}}
  {{}}driver.Navigate().Forward();{{}}
  {{}}driver.navigate.forward{{}}
  {{}}await driver.navigate().forward();{{}}
  {{}}driver.navigate().forward();{{}}
{{}}

### Refresh

Refresh the current page:

{{}}
  {{}}driver.navigate().refresh();{{}}
  {{}}driver.refresh(){{}}
  {{}}driver.Navigate().Refresh();{{}}
  {{}}driver.navigate.refresh{{}}
  {{}}await driver.navigate().refresh();{{}}
  {{}}driver.navigate().refresh(){{}}
{{}}

### Get title

You can read the current page title from the browser:

{{}}
  {{}}driver.getTitle();{{}}
  {{}}driver.title{{}}
  {{}}driver.Title;{{}}
  {{}}driver.title{{}}
  {{}}await driver.getTitle();{{}}
  {{}}driver.getTitle(){{}}
{{}}

## Windows and tabs
WebDriver doesn't make the distinction between windows and tabs. If
your site opens a new tab or window, Selenium will let you work with it
using a window handle.  Each window has a unique identifier which remains
persistent in a single session. You can get the window handle of the
current window by using:

{{}}
  {{}}driver.getWindowHandle();{{}}
  {{}}driver.current_window_handle{{}}
  {{}}driver.CurrentWindowHandle;{{}}
  {{}}driver.window_handle{{}}
  {{}}await driver.getWindowHandle();{{}}
  {{}}driver.getWindowHandle(){{}}
{{}}

### Switching windows or tabs

Clicking a link which opens in a
 new window
will focus the new window or tab on screen, but WebDriver will not know which
window the Operating System considers active.  To work with the new window
you will need to switch to it. If you have only two tabs or windows open,
and you know which window you start with, by the process of elimination
you can loop over both windows or tabs that WebDriver can see, and switch
to the one which is not the original.

{{}}
  {{}}
//Store the ID of the original window
String originalWindow = driver.getWindowHandle();

//Check we don't have other windows open already
assert driver.getWindowHandles().size() == 1;

//Click the link which opens in a new window
driver.findElement(By.linkText("new window")).click();

//Wait for the new window or tab
wait.until(numberOfWindowsToBe(2));

//Loop through until we find a new window handle
for (String windowHandle : driver.getWindowHandles()) {
    if(!originalWindow.contentEquals(windowHandle)) {
        driver.switchTo().window(windowHandle);
        break;
    }
}

//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"));
  {{}}
  {{}}
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Start the driver
with webdriver.Firefox() as driver:
    # Open URL
    driver.get("https://seleniumhq.github.io/docs/wd.html")

    # Setup wait for later
    wait = WebDriverWait(driver, 10)

    # Store the ID of the original window
    original_window = driver.current_window_handle

    # Check we don't have other windows open already
    assert len(driver.window_handles) == 1

    # Click the link which opens in a new window
    driver.find_element_by_link_text("new window").click()

    # Wait for the new window or tab
    wait.until(EC.number_of_windows_to_be(2))

    # Loop through until we find a new window handle
    for window_handle in driver.window_handles:
        if window_handle != original_window:
            driver.switch_to.window(window_handle)
            break

    # Wait for the new tab to finish loading content
    wait.until(EC.title_is("Selenium documentation"))
  {{}}
  {{}}
//Store the ID of the original window
string originalWindow = driver.CurrentWindowHandle;

//Check we don't have other windows open already
Assert.AreEqual(driver.WindowHandles.Count, 1);

//Click the link which opens in a new window
driver.FindElement(By.LinkText("new window")).Click();

//Wait for the new window or tab
wait.Until(wd => wd.WindowHandles.Count == 2);

//Loop through until we find a new window handle
foreach(string window in driver.WindowHandles)
{
    if(originalWindow != window)
    {
        driver.SwitchTo().Window(window);
        break;
    }
}
//Wait for the new tab to finish loading content
wait.Until(wd => wd.Title == "Selenium documentation");
  {{}}
  {{}}
#Store the ID of the original window
original_window = driver.window_handle

#Check we don't have other windows open already
assert(driver.window_handles.length == 1, 'Expected one window')

#Click the link which opens in a new window
driver.find_element(link: 'new window').click

#Wait for the new window or tab
wait.until { driver.window_handles.length == 2 }

#Loop through until we find a new window handle
driver.window_handles.each do |handle|
    if handle != original_window
        driver.switch_to.window handle
        break
    end
end

#Wait for the new tab to finish loading content
wait.until { driver.title == 'Selenium documentation'}
  {{}}
  {{}}
//Store the ID of the original window
const originalWindow = await driver.getWindowHandle();

//Check we don't have other windows open already
assert((await driver.getAllWindowHandles()).length === 1);

//Click the link which opens in a new window
await driver.findElement(By.linkText('new window')).click();

//Wait for the new window or tab
await driver.wait(
    async () => (await driver.getAllWindowHandles()).length === 2,
    10000
  );

//Loop through until we find a new window handle
const windows = await driver.getAllWindowHandles();
windows.forEach(async handle => {
  if (handle !== originalWindow) {
    await driver.switchTo().window(handle);
  }
});

//Wait for the new tab to finish loading content
await driver.wait(until.titleIs('Selenium documentation'), 10000);
  {{}}
  {{}}
//Store the ID of the original window
val originalWindow = driver.getWindowHandle()

//Check we don't have other windows open already
assert(driver.getWindowHandles().size() === 1)

//Click the link which opens in a new window
driver.findElement(By.linkText("new window")).click()

//Wait for the new window or tab
wait.until(numberOfWindowsToBe(2))

//Loop through until we find a new window handle
for (windowHandle in driver.getWindowHandles()) {
      if (!originalWindow.contentEquals(windowHandle)) {
          driver.switchTo().window(windowHandle)
           break
      }
}

//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"))

  {{}}
{{}}

### Closing a window or tab

When you are finished with a window or tab _and_ it is not the
last window or tab open in your browser, you should close it and switch
back to the window you were using previously.  Assuming you followed the
code sample in the previous section you will have the previous window
handle stored in a variable. Put this together and you will get:

{{}}
  {{}}
//Close the tab or window
driver.close();

//Switch back to the old tab or window
driver.switchTo().window(originalWindow);
  {{}}
  {{}}
#Close the tab or window
driver.close()

#Switch back to the old tab or window
driver.switch_to.window(original_window)
  {{}}
  {{}}
//Close the tab or window
driver.Close();

//Switch back to the old tab or window
driver.SwitchTo().Window(originalWindow);
  {{}}
  {{}}
#Close the tab or window
driver.close

#Switch back to the old tab or window
driver.switch_to.window original_window
  {{}}
  {{}}
//Close the tab or window
await driver.close();

//Switch back to the old tab or window
await driver.switchTo().window(originalWindow);
  {{}}
  {{}}
//Close the tab or window
driver.close()

//Switch back to the old tab or window
driver.switchTo().window(originalWindow)

  {{}}
{{}}

Forgetting to switch back to another window handle after closing a
window will leave WebDriver executing on the now closed page, and will
trigger a **No Such Window Exception**. You must switch
back to a valid window handle in order to continue execution.

### Quitting the browser at the end of a session

When you are finished with the browser session you should call quit,
instead of close:

{{}}
  {{}}driver.quit();{{}}
  {{}}driver.quit(){{}}
  {{}}driver.Quit();{{}}
  {{}}driver.quit{{}}
  {{}}await driver.quit();{{}}
  {{}}driver.quit(){{}}
{{}}

* Quit will:
  * Close all the windows and tabs associated with that WebDriver
  session
  * The browser process
  * The background driver process
  * Notify Selenium Grid that the browser is no longer in use so it can
   be used by another session (if you are using Selenium Grid)

Failure to call quit will leave extra background processes and ports
running on your machine which could cause you problems later.

Some test frameworks offer methods and annotations which you can hook
into to tear down at the end of a test.

{{}}
  {{}}
/**
 * Example using JUnit
 * https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
 */
@AfterAll
public static void tearDown() {
    driver.quit();
}
  {{}}
  {{}}
# We don't have a Python code sample yet -  Help us out and raise a PR
  {{}}
  {{}}
/*
    Example using Visual Studio's UnitTesting
    https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.aspx
*/
[TestCleanup]
public void TearDown()
{
    driver.Quit();
}
  {{}}
  {{}}
# We don't have a Ruby code sample yet -  Help us out and raise a PR
  {{}}
  {{}}
/**
 * Example using Mocha
 * https://mochajs.org/#hooks
 */
after('Tear down', async function () {
  await driver.quit();
});
  {{}}
  {{}}

/**
 * Example using JUnit
 * https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
 */
@AfterAll
fun tearDown() {
    driver.quit()
}
  {{}}
{{}}

If not running WebDriver in a test context, you may consider using
`try  / finally` which is offered by most languages so that an exception
will still clean up the WebDriver session.

{{}}
  {{}}
try {
    //WebDriver code here...
} finally {
    driver.quit();
}
  {{}}
  {{}}
try:
    #WebDriver code here...
finally:
    driver.quit()
  {{}}
  {{}}
try {
    //WebDriver code here...
} finally {
    driver.Quit();
}
  {{}}
  {{}}
begin
    #WebDriver code here...
ensure
    driver.quit
end
  {{}}
  {{}}
try {
    //WebDriver code here...
} finally {
    await driver.quit();
}
  {{}}
  {{}}
try {
    //WebDriver code here...
} finally {
    driver.quit()
}
  {{}}
{{}}

Python's WebDriver now supports the python context manager,
which when using the with keyword can automatically quit the driver at
the end of execution.

```python
with webdriver.Firefox() as driver:
  # WebDriver code here...

# WebDriver will automatically quit after indentation
```

## Frames and Iframes
Frames are a now deprecated means of building a site layout from
multiple documents on the same domain. You are unlikely to work with
them unless you are working with an pre HTML5 webapp.  Iframes allow
the insertion of a document from an entirely different domain, and are
still commonly used.

If you need to work with frames or iframes, Webdriver allows you to
work with them in the same way. Consider a button within an iframe.
If we inspect the element using the browser development tools, we might
see the following:

```html
<div id="modal">
  <iframe id="buttonframe" name="myframe"  src="https://seleniumhq.github.io/docs/iframe.html">
   <button>Click here</button>
 </iframe>
</div>
```

If it wasn't for the iframe we would expect to click on the button
using something like:

{{}}
  {{}}
//This won't work
driver.findElement(By.tagName("button")).click();
  {{}}
  {{}}
# This Wont work
driver.find_element_by_tag_name('button').click()
  {{}}
  {{}}
//This won't work
driver.FindElement(By.TagName("button")).Click();
  {{}}
  {{}}
# This won't work
driver.find_element(:tag_name,'button').click
  {{}}
  {{}}
// This won't work
await driver.findElement(By.css('button')).click();
  {{}}
  {{}}
//This won't work
driver.findElement(By.tagName("button")).click()
  {{}}
{{}}

However, if there are no buttons outside of the iframe, you might
instead get a _no such element_ error. This happens because Selenium is
only aware of the elements in the top level document. To interact with
the button, we will need to first switch to the frame, in a similar way
to how we switch windows. WebDriver offers three ways of switching to
a frame.

### Using a WebElement

Switching using a WebElement is the most flexible option. You can
find the frame using your preferred selector and switch to it.

{{}}
  {{}}
//Store the web element
WebElement iframe = driver.findElement(By.cssSelector("#modal>iframe"));

//Switch to the frame
driver.switchTo().frame(iframe);

//Now we can click the button
driver.findElement(By.tagName("button")).click();
  {{}}
  {{}}
# Store iframe web element
iframe = driver.find_element_by_css_selector("#modal > iframe")

# switch to selected iframe
driver.switch_to.frame(iframe)

# Now click on button
driver.find_element_by_tag_name('button').click()
  {{}}
  {{}}
//Store the web element
IWebElement iframe = driver.FindElement(By.CssSelector("#modal>iframe"));

//Switch to the frame
driver.SwitchTo().Frame(iframe);

//Now we can click the button
driver.FindElement(By.TagName("button")).Click();
  {{}}
  {{}}
# Store iframe web element
iframe = driver.find_element(:css,'#modal > iframe')

# Switch to the frame
driver.switch_to.frame iframe

# Now, Click on the button
driver.find_element(:tag_name,'button').click
  {{}}
  {{}}
// Store the web element
const iframe = await driver.findElement(By.css('#modal > iframe'));

// Switch to the frame
await driver.switchTo().frame(iframe);

// Now we can click the button
await driver.findElement(By.css('button')).click();
  {{}}
  {{}}
//Store the web element
WebElement iframe = driver.findElement(By.cssSelector("#modal>iframe"))

//Switch to the frame
driver.switchTo().frame(iframe)

//Now we can click the button
driver.findElement(By.tagName("button")).click()
  {{}}
{{}}

### Using a name or ID
If your frame or iframe has an id or name attribute, this can be used
instead.  If the name or ID is not unique on the page, then the first
one found will be switched to.

{{}}
  {{}}
//Using the ID
driver.switchTo().frame("buttonframe");

//Or using the name instead
driver.switchTo().frame("myframe");

//Now we can click the button
driver.findElement(By.tagName("button")).click();
  {{}}
  {{}}
# Switch frame by id
driver.switch_to.frame('buttonframe')

# Now, Click on the button
driver.find_element_by_tag_name('button').click()
  {{}}
  {{}}
//Using the ID
driver.SwitchTo().Frame("buttonframe");

//Or using the name instead
driver.SwitchTo().Frame("myframe");

//Now we can click the button
driver.FindElement(By.TagName("button")).Click();
  {{}}
  {{}}
# Switch by ID
driver.switch_to.frame 'buttonframe'

# Now, Click on the button
driver.find_element(:tag_name,'button').click
  {{}}
  {{}}
// Using the ID
await driver.switchTo().frame('buttonframe');

// Or using the name instead
await driver.switchTo().frame('myframe');

// Now we can click the button
await driver.findElement(By.css('button')).click();
  {{}}
  {{}}
//Using the ID
driver.switchTo().frame("buttonframe")

//Or using the name instead
driver.switchTo().frame("myframe")

//Now we can click the button
driver.findElement(By.tagName("button")).click()
  {{}}
{{}}

### Using an index

It is also possible to use the index of the frame, such as can be
queried using _window.frames_ in JavaScript.

{{}}
  {{}}
// Switches to the second frame
driver.switchTo().frame(1);
  {{}}
  {{}}
# Switch to the second frame
driver.switch_to.frame(1)
  {{}}
  {{}}
// Switches to the second frame
driver.SwitchTo().Frame(1);
  {{}}
  {{}}
# switching to second iframe based on index
iframe = driver.find_elements_by_tag_name('iframe')[1]

# switch to selected iframe
driver.switch_to.frame(iframe)
  {{}}
  {{}}
// Switches to the second frame
await driver.switchTo().frame(1);
  {{}}
  {{}}
// Switches to the second frame
driver.switchTo().frame(1)
  {{}}
{{}}

### Leaving a frame

To leave an iframe or frameset, switch back to the default content
like so:

{{}}
  {{}}
// Return to the top level
driver.switchTo().defaultContent();
  {{}}
  {{}}
# switch back to default content
driver.switch_to.default_content()
  {{}}
  {{}}
// Return to the top level
driver.SwitchTo().DefaultContent();
  {{}}
  {{}}
# Return to the top level
driver.switch_to.default_content
  {{}}
  {{}}
// Return to the top level
await driver.switchTo().defaultContent();
  {{}}
  {{}}
// Return to the top level
driver.switchTo().defaultContent()
  {{}}
{{}}

## Window management
Screen resolution can impact how your web application renders, so
WebDriver provides mechanisms for moving and resizing the browser
window.

### Get window size
Fetches the size of the browser window in pixels.

{{}}
  {{}}
//Access each dimension individually
int width = driver.manage().window().getSize().getWidth();
int height = driver.manage().window().getSize().getHeight();

//Or store the dimensions and query them later
Dimension size = driver.manage().window().getSize();
int width1 = size.getWidth();
int height1 = size.getHeight();
  {{}}
  {{}}
# Access each dimension individually
width = driver.get_window_size().get("width")
height = driver.get_window_size().get("height")

# Or store the dimensions and query them later
size = driver.get_window_size()
width1 = size.get("width")
height1 = size.get("height")
  {{}}
  {{}}
//Access each dimension individually
int width = driver.Manage().Window.Size.Width;
int height = driver.Manage().Window.Size.Height;

//Or store the dimensions and query them later
System.Drawing.Size size = driver.Manage().Window.Size;
int width1 = size.Width;
int height1 = size.Height;
  {{}}
  {{}}
# Access each dimension individually
width = driver.manage.window.size.width
height = driver.manage.window.size.height

# Or store the dimensions and query them later
size = driver.manage.window.size
width1 = size.width
height1 = size.height
  {{}}
  {{}}
// Access each dimension individually
const { width, height } = await driver.manage().window().getRect();

// Or store the dimensions and query them later
const rect = await driver.manage().window().getRect();
const width1 = rect.width;
const height1 = rect.height;
  {{}}
  {{}}
//Access each dimension individually
val width = driver.manage().window().getSize().getWidth()
val height = driver.manage().window().getSize().getHeight()

//Or store the dimensions and query them later
val size = driver.manage().window().getSize()
val width1 = size.getWidth()
val height1 = size.getHeight()
  {{}}
{{}}

### Set window size

Restores the window and sets the window size.
{{}}
  {{}}driver.manage().window().setSize(new Dimension(1024, 768));{{}}
  {{}}driver.set_window_size(1024, 768){{}}
  {{}}driver.Manage().Window.Size = new Size(1024, 768);{{}}
  {{}}driver.manage.window.resize_to(1024,768){{}}
  {{}}await driver.manage().window().setRect({ width: 1024, height: 768 });{{}}
  {{}}driver.manage().window().size(Dimension(1024, 768)){{}}
{{}}

### Get window position

Fetches the coordinates of the top left coordinate of the browser window.

{{}}
  {{}}
// Access each dimension individually
int x = driver.manage().window().getPosition().getX();
int y = driver.manage().window().getPosition().getY();

// Or store the dimensions and query them later
Point position = driver.manage().window().getPosition();
int x1 = position.getX();
int y1 = position.getY();
  {{}}
  {{}}
# Access each dimension individually
x = driver.get_window_position().get('x')
y = driver.get_window_position().get('y')

# Or store the dimensions and query them later
position = driver.get_window_position()
x1 = position.get('x')
y1 = position.get('y')
  {{}}
  {{}}
//Access each dimension individually
int x = driver.Manage().Window.Position.X;
int y = driver.Manage().Window.Position.Y;

//Or store the dimensions and query them later
Point position = driver.Manage().Window.Position;
int x1 = position.X;
int y1 = position.Y;
  {{}}
  {{}}
# We don't have a Ruby code sample yet -  Help us out and raise a PR
  {{}}
  {{}}
// Access each dimension individually
const { x, y } = await driver.manage().window().getRect();

// Or store the dimensions and query them later
const rect = await driver.manage().window().getRect();
const x1 = rect.x;
const y1 = rect.y;
  {{}}
  {{}}
// Access each dimension individually
val x = driver.manage().window().position.x
val y = driver.manage().window().position.y

// Or store the dimensions and query them later
val position = driver.manage().window().position
val x1 = position.x
int y1 = position.y

  {{}}
{{}}

## Set window position

Moves the window to the chosen position.

{{}}
  {{}}
// Move the window to the top left of the primary monitor
driver.manage().window().setPosition(new Point(0, 0));
  {{}}
  {{}}
# Move the window to the top left of the primary monitor
driver.set_window_position(0, 0)
  {{}}
  {{}}
// Move the window to the top left of the primary monitor
driver.Manage().Window.Position = new Point(0, 0);
  {{}}
  {{}}
driver.manage.window.move_to(0,0)
  {{}}
  {{}}
// Move the window to the top left of the primary monitor
await driver.manage().window().setRect({ x: 0, y: 0 });
  {{}}
  {{}}
// Move the window to the top left of the primary monitor
driver.manage().window().position = Point(0,0)
    {{}}
{{}}

### Maximise window
Enlarges the window. For most operating systems, the window will fill
the screen, without blocking the operating system's own menus and
toolbars.

{{}}
  {{}}driver.manage().window().maximize();{{}}
  {{}}driver.maximize_window(){{}}
  {{}}driver.Manage().Window.Maximize();{{}}
  {{}}driver.manage.window.maximize{{}}
  {{}}await driver.manage().window().maximize();{{}}
  {{}}driver.manage().window().maximize(){{}}
{{}}

### Fullscreen window

Fills the entire screen, similar to pressing F11 in most browsers.

{{}}
  {{}}driver.manage().window().fullscreen();{{}}
  {{}}driver.fullscreen_window(){{}}
  {{}}driver.Manage().Window.FullScreen();{{}}
  {{}}driver.manage.window.full_screen{{}}
  {{}}await driver.manage().window().fullscreen();{{}}
  {{}}driver.manage().window().fullscreen(){{}}
{{}}


text:
package com.amazonaws.services.devicefarm.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.devicefarm.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * UploadMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UploadMarshaller {

    private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("arn").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("name").build();
    private static final MarshallingInfo<java.util.Date> CREATED_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("created").build();
    private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("type").build();
    private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("status").build();
    private static final MarshallingInfo<String> URL_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("url").build();
    private static final MarshallingInfo<String> METADATA_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("metadata").build();
    private static final MarshallingInfo<String> CONTENTTYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("contentType").build();
    private static final MarshallingInfo<String> MESSAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("message").build();

    private static final UploadMarshaller instance = new UploadMarshaller();

    public static UploadMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Upload upload, ProtocolMarshaller protocolMarshaller) {

        if (upload == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(upload.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(upload.getName(), NAME_BINDING);
            protocolMarshaller.marshall(upload.getCreated(), CREATED_BINDING);
            protocolMarshaller.marshall(upload.getType(), TYPE_BINDING);
            protocolMarshaller.marshall(upload.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(upload.getUrl(), URL_BINDING);
            protocolMarshaller.marshall(upload.getMetadata(), METADATA_BINDING);
            protocolMarshaller.marshall(upload.getContentType(), CONTENTTYPE_BINDING);
            protocolMarshaller.marshall(upload.getMessage(), MESSAGE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.google.cloud.teleport.spanner.ddl;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.text.IsEqualCompressingWhiteSpace.equalToCompressingWhiteSpace;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

import com.google.cloud.spanner.Dialect;
import com.google.cloud.teleport.spanner.common.Type;
import com.google.cloud.teleport.spanner.ddl.IndexColumn.IndexColumnsBuilder;
import com.google.cloud.teleport.spanner.ddl.IndexColumn.Order;
import com.google.cloud.teleport.spanner.proto.ExportProtos.Export;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;

/** Test coverage for {@link Ddl}. */
public class DdlTest {

  @Test
  public void emptyDb() {
    Ddl empty = Ddl.builder().build();
    assertThat(empty.allTables(), empty());
    assertThat(empty.prettyPrint(), equalTo(""));
    assertTrue(empty.equals(empty));
    assertNotNull(empty.hashCode());
  }

  @Test
  public void pgEmptyDb() {
    Ddl empty = Ddl.builder(Dialect.POSTGRESQL).build();
    assertEquals(empty.dialect(), Dialect.POSTGRESQL);
    assertThat(empty.allTables(), empty());
    assertThat(empty.prettyPrint(), equalTo(""));
    assertFalse(empty.equals(null));
    assertFalse(empty.equals(Boolean.TRUE));
    assertNotNull(empty.hashCode());
  }

  @Test
  public void simple() {
    Ddl.Builder builder = Ddl.builder();
    builder
        .createTable("Users")
        .column("id")
        .int64()
        .notNull()
        .endColumn()
        .column("first_name")
        .string()
        .size(10)
        .defaultExpression("'John'")
        .endColumn()
        .column("last_name")
        .type(Type.string())
        .max()
        .endColumn()
        .column("full_name")
        .type(Type.string())
        .max()
        .generatedAs("CONCAT(first_name, ' ', last_name)")
        .stored()
        .endColumn()
        .primaryKey()
        .asc("id")
        .end()
        .indexes(ImmutableList.of("CREATE INDEX `UsersByFirstName` ON `Users` (`first_name`)"))
        .foreignKeys(
            ImmutableList.of(
                "ALTER TABLE `Users` ADD CONSTRAINT `fk` FOREIGN KEY (`first_name`)"
                    + " REFERENCES `AllowedNames` (`first_name`)"))
        .checkConstraints(ImmutableList.of("CONSTRAINT `ck` CHECK (`first_name` != `last_name`)"))
        .endTable();
    Export export =
        Export.newBuilder()
            .addDatabaseOptions(
                Export.DatabaseOption.newBuilder()
                    .setOptionName("version_retention_period")
                    .setOptionValue("4d")
                    .setOptionType("STRING")
                    .build())
            .build();
    builder.mergeDatabaseOptions(export.getDatabaseOptionsList());
    Ddl ddl = builder.build();
    assertThat(
        ddl.prettyPrint(),
        equalToCompressingWhiteSpace(
            "ALTER DATABASE `%db_name%` SET OPTIONS ( version_retention_period = \"4d\" )"
                + " CREATE TABLE `Users` ("
                + " `id` INT64 NOT NULL,"
                + " `first_name` STRING(10) DEFAULT ('John'),"
                + " `last_name` STRING(MAX),"
                + " `full_name` STRING(MAX) AS (CONCAT(first_name, ' ', last_name)) STORED,"
                + " CONSTRAINT `ck` CHECK (`first_name` != `last_name`),"
                + " ) PRIMARY KEY (`id` ASC)"
                + " CREATE INDEX `UsersByFirstName` ON `Users` (`first_name`)"
                + " ALTER TABLE `Users` ADD CONSTRAINT `fk` FOREIGN KEY (`first_name`)"
                + " REFERENCES `AllowedNames` (`first_name`)"));
    List<String> statements = ddl.statements();
    assertEquals(4, statements.size());
    assertThat(
        statements.get(0),
        equalToCompressingWhiteSpace(
            " CREATE TABLE `Users` ("
                + " `id` INT64 NOT NULL,"
                + " `first_name` STRING(10) DEFAULT ('John'),"
                + " `last_name` STRING(MAX),"
                + " `full_name` STRING(MAX) AS (CONCAT(first_name, ' ', last_name)) STORED,"
                + " CONSTRAINT `ck` CHECK (`first_name` != `last_name`),"
                + " ) PRIMARY KEY (`id` ASC)"));
    assertThat(
        statements.get(1),
        equalToCompressingWhiteSpace(" CREATE INDEX `UsersByFirstName` ON `Users` (`first_name`)"));
    assertThat(
        statements.get(2),
        equalToCompressingWhiteSpace(
            "ALTER TABLE `Users` ADD CONSTRAINT `fk` FOREIGN KEY (`first_name`) REFERENCES"
                + " `AllowedNames` (`first_name`)"));
    assertThat(
        statements.get(3),
        equalToCompressingWhiteSpace(
            "ALTER DATABASE `%db_name%` SET OPTIONS ( version_retention_period = \"4d\" )"));
    assertNotNull(ddl.hashCode());
  }

  @Test
  public void pgSimple() {
    Ddl.Builder builder = Ddl.builder(Dialect.POSTGRESQL);
    builder
        .createTable("Users")
        .column("id")
        .pgInt8()
        .notNull()
        .endColumn()
        .column("first_name")
        .pgVarchar()
        .size(10)
        .defaultExpression("John")
        .endColumn()
        .column("last_name")
        .type(Type.pgVarchar())
        .max()
        .defaultExpression("Lennon")
        .endColumn()
        .column("full_name")
        .type(Type.pgVarchar())
        .max()
        .generatedAs("CONCAT(first_name, ' ', last_name)")
        .stored()
        .endColumn()
        .primaryKey()
        .asc("id")
        .end()
        .indexes(
            ImmutableList.of("CREATE INDEX \"UsersByFirstName\" ON \"Users\" (\"first_name\")"))
        .foreignKeys(
            ImmutableList.of(
                "ALTER TABLE \"Users\" ADD CONSTRAINT \"fk\" FOREIGN KEY (\"first_name\")"
                    + " REFERENCES \"AllowedNames\" (\"first_name\")"))
        .checkConstraints(
            ImmutableList.of("CONSTRAINT \"ck\" CHECK (\"first_name\" != \"last_name\")"))
        .endTable();
    Export export =
        Export.newBuilder()
            .addDatabaseOptions(
                Export.DatabaseOption.newBuilder()
                    .setOptionName("version_retention_period")
                    .setOptionValue("4d")
                    .setOptionType("character varying")
                    .build())
            .build();
    builder.mergeDatabaseOptions(export.getDatabaseOptionsList());
    Ddl ddl = builder.build();
    assertThat(
        ddl.prettyPrint(),
        equalToCompressingWhiteSpace(
            "ALTER DATABASE \"%db_name%\" SET spanner.version_retention_period = '4d'"
                + " CREATE TABLE \"Users\" ("
                + " \"id\" bigint NOT NULL,"
                + " \"first_name\" character varying(10) DEFAULT John,"
                + " \"last_name\" character varying DEFAULT Lennon,"
                + " \"full_name\" character varying GENERATED ALWAYS AS"
                + " (CONCAT(first_name, ' ', last_name)) STORED,"
                + " CONSTRAINT \"ck\" CHECK (\"first_name\" != \"last_name\"),"
                + " PRIMARY KEY (\"id\")"
                + " ) "
                + " CREATE INDEX \"UsersByFirstName\" ON \"Users\" (\"first_name\")"
                + " ALTER TABLE \"Users\" ADD CONSTRAINT \"fk\" FOREIGN KEY (\"first_name\")"
                + " REFERENCES \"AllowedNames\" (\"first_name\")"));
    assertNotNull(ddl.hashCode());
  }

  @Test
  public void interleaves() {
    Ddl ddl =
        Ddl.builder()
            .createTable("Users")
            .column("id")
            .int64()
            .notNull()
            .endColumn()
            .column("first_name")
            .string()
            .size(10)
            .endColumn()
            .column("last_name")
            .type(Type.string())
            .max()
            .endColumn()
            .primaryKey()
            .asc("id")
            .end()
            .endTable()
            .createTable("Account")
            .column("id")
            .int64()
            .notNull()
            .endColumn()
            .column("balanceId")
            .int64()
            .notNull()
            .endColumn()
            .column("balance")
            .float64()
            .notNull()
            .endColumn()
            .primaryKey()
            .asc("id")
            .end()
            .interleaveInParent("Users")
            .onDeleteCascade()
            .endTable()
            .build();
    assertThat(
        ddl.prettyPrint(),
        equalToCompressingWhiteSpace(
            "CREATE TABLE `Users` ("
                + " `id`                                    INT64 NOT NULL,"
                + " `first_name`                            STRING(10),"
                + " `last_name`                             STRING(MAX),"
                + " ) PRIMARY KEY (`id` ASC)"
                + " CREATE TABLE `Account` ("
                + " `id`                                    INT64 NOT NULL,"
                + " `balanceId`                             INT64 NOT NULL,"
                + " `balance`                               FLOAT64 NOT NULL,"
                + " ) PRIMARY KEY (`id` ASC), "
                + " INTERLEAVE IN PARENT `Users` ON DELETE CASCADE"));
    Collection<Table> rootTables = ddl.rootTables();
    assertEquals(1, rootTables.size());
    assertEquals("Users", rootTables.iterator().next().name());
    HashMultimap<Integer, String> perLevelView = ddl.perLevelView();
    assertEquals(2, perLevelView.size());
    assertTrue(perLevelView.containsKey(0));
    assertEquals("users", perLevelView.get(0).iterator().next());
    assertTrue(perLevelView.containsKey(1));
    assertEquals("account", perLevelView.get(1).iterator().next());
    assertNotNull(ddl.hashCode());
  }

  @Test
  public void pgInterleaves() {
    Ddl ddl =
        Ddl.builder(Dialect.POSTGRESQL)
            .createTable("Users")
            .column("id")
            .pgInt8()
            .notNull()
            .endColumn()
            .column("first_name")
            .pgVarchar()
            .size(10)
            .endColumn()
            .column("last_name")
            .type(Type.pgVarchar())
            .max()
            .endColumn()
            .primaryKey()
            .asc("id")
            .end()
            .endTable()
            .createTable("Account")
            .column("id")
            .pgInt8()
            .notNull()
            .endColumn()
            .column("balanceId")
            .pgInt8()
            .notNull()
            .endColumn()
            .column("balance")
            .pgFloat8()
            .notNull()
            .endColumn()
            .primaryKey()
            .asc("id")
            .end()
            .interleaveInParent("Users")
            .onDeleteCascade()
            .endTable()
            .build();
    assertThat(
        ddl.prettyPrint(),
        equalToCompressingWhiteSpace(
            "CREATE TABLE \"Users\" ("
                + " \"id\"                                    bigint NOT NULL,"
                + " \"first_name\"                            character varying(10),"
                + " \"last_name\"                             character varying,"
                + " PRIMARY KEY (\"id\")"
                + " ) "
                + " CREATE TABLE \"Account\" ("
                + " \"id\"                                    bigint NOT NULL,"
                + " \"balanceId\"                             bigint NOT NULL,"
                + " \"balance\"                               double precision NOT NULL,"
                + " PRIMARY KEY (\"id\")"
                + " ) "
                + " INTERLEAVE IN PARENT \"Users\" ON DELETE CASCADE"));
    assertNotNull(ddl.hashCode());
  }

  @Test
  public void testDatabaseOptions() {
    Ddl.Builder builder = Ddl.builder();
    List<Export.DatabaseOption> dbOptionList = new ArrayList<>();
    dbOptionList.add(
        Export.DatabaseOption.newBuilder()
            .setOptionName("version_retention_period")
            .setOptionValue("4d")
            .setOptionType("STRING")
            .build());
    dbOptionList.add(
        Export.DatabaseOption.newBuilder()
            .setOptionName("optimizer_version")
            .setOptionValue("2")
            .build());
    builder.mergeDatabaseOptions(dbOptionList);
    Ddl ddl = builder.build();
    List<String> optionStatements = ddl.setOptionsStatements("database_id");
    assertThat(optionStatements.size(), is(1));
    assertThat(
        optionStatements.get(0),
        is("ALTER DATABASE `database_id` SET OPTIONS ( version_retention_period = \"4d\" )"));
    assertNotNull(ddl.hashCode());
  }

  @Test
  public void pgTestDatabaseOptions() {
    Ddl.Builder builder = Ddl.builder(Dialect.POSTGRESQL);
    List<Export.DatabaseOption> dbOptionList = new ArrayList<>();
    dbOptionList.add(
        Export.DatabaseOption.newBuilder()
            .setOptionName("version_retention_period")
            .setOptionValue("4d")
            .setOptionType("character varying")
            .build());
    dbOptionList.add(
        Export.DatabaseOption.newBuilder()
            .setOptionName("optimizer_version")
            .setOptionValue("2")
            .build());
    builder.mergeDatabaseOptions(dbOptionList);
    Ddl ddl = builder.build();
    List<String> optionStatements = ddl.setOptionsStatements("database_id");
    assertThat(optionStatements.size(), is(1));
    assertThat(
        optionStatements.get(0),
        is("ALTER DATABASE \"database_id\" SET spanner.version_retention_period = '4d'"));
    assertNotNull(ddl.hashCode());
  }

  @Test
  public void pgTestIndex() {
    Index.Builder builder =
        Index.builder(Dialect.POSTGRESQL)
            .name("user_index")
            .table("User")
            .unique()
            .filter("\"first_name\" IS NOT NULL AND \"last_name\" IS NOT NULL");
    builder
        .columns()
        .create()
        .name("first_name")
        .asc()
        .endIndexColumn()
        .create()
        .name("last_name")
        .desc()
        .endIndexColumn()
        .create()
        .name("full_name")
        .storing()
        .endIndexColumn()
        .end();
    Index index = builder.build();
    assertThat(
        index.prettyPrint(),
        equalToCompressingWhiteSpace(
            "CREATE UNIQUE INDEX \"user_index\" ON \"User\"(\"first_name\" ASC,"
                + " \"last_name\" DESC) INCLUDE (\"full_name\") WHERE \"first_name\" IS"
                + " NOT NULL AND \"last_name\" IS NOT NULL"));
    assertTrue(index.equals(index));
    assertFalse(index.equals(Boolean.TRUE));
    builder = index.autoToBuilder();
    builder
        .columns()
        .create()
        .name("first_name")
        .asc()
        .endIndexColumn()
        .create()
        .name("last_name")
        .desc()
        .endIndexColumn()
        .create()
        .name("full_name")
        .storing()
        .endIndexColumn()
        .end();
    Index index1 = builder.build();
    assertTrue(index.equals(index1));
    assertNotNull(index.hashCode());
  }

  @Test
  public void pgTestIndexNullsOrder() {
    Index.Builder builder =
        Index.builder(Dialect.POSTGRESQL).name("user_index").table("User").unique();
    builder
        .columns()
        .create()
        .name("first_name")
        .asc()
        .nullsFirst()
        .endIndexColumn()
        .create()
        .name("last_name")
        .desc()
        .nullsLast()
        .endIndexColumn()
        .create()
        .name("first_nick_name")
        .asc()
        .nullsLast()
        .endIndexColumn()
        .create()
        .name("last_nick_name")
        .desc()
        .nullsFirst()
        .endIndexColumn()
        .create()
        .name("full_name")
        .storing()
        .endIndexColumn()
        .end();
    Index index = builder.build();
    assertThat(
        index.prettyPrint(),
        equalToCompressingWhiteSpace(
            "CREATE UNIQUE INDEX \"user_index\" ON \"User\"(\"first_name\" ASC NULLS FIRST,"
                + " \"last_name\" DESC NULLS LAST, \"first_nick_name\" ASC NULLS LAST,"
                + " \"last_nick_name\" DESC NULLS FIRST) INCLUDE (\"full_name\")"));
    assertNotNull(index.hashCode());
  }

  @Test
  public void pgTestCheckConstraint() {
    CheckConstraint checkConstraint =
        CheckConstraint.builder(Dialect.POSTGRESQL)
            .name("name_check")
            .expression("\"first_name\" != \"last_name\"")
            .build();
    assertThat(
        checkConstraint.prettyPrint(),
        equalToCompressingWhiteSpace(
            "CONSTRAINT \"name_check\" CHECK (\"first_name\" != \"last_name\")"));
    assertNotNull(checkConstraint.hashCode());
  }

  @Test
  public void pgTestForeignKey() {
    ForeignKey.Builder builder =
        ForeignKey.builder(Dialect.POSTGRESQL)
            .name("account_to_user")
            .table("Account")
            .referencedTable("User");
    builder.columnsBuilder().add("account_id", "owner_name");
    builder.referencedColumnsBuilder().add("user_id", "full_name");
    ForeignKey foreignKey = builder.build();
    assertThat(
        foreignKey.prettyPrint(),
        equalToCompressingWhiteSpace(
            "ALTER TABLE \"Account\" ADD CONSTRAINT \"account_to_user\" FOREIGN KEY"
                + " (\"account_id\", \"owner_name\") REFERENCES \"User\" (\"user_id\","
                + " \"full_name\")"));
    assertNotNull(foreignKey.hashCode());
  }

  @Test
  public void testView() {
    View view = View.builder().name("user_view").query("SELECT * FROM `User`").build();
    assertThat(
        view.prettyPrint(),
        equalToCompressingWhiteSpace("CREATE VIEW `user_view` AS SELECT * FROM `User`"));
  }

  @Test
  public void pgTestView() {
    View view =
        View.builder(Dialect.POSTGRESQL)
            .name("user_view")
            .query("SELECT * FROM \"User\"")
            .security(View.SqlSecurity.INVOKER)
            .build();
    assertThat(
        view.prettyPrint(),
        equalToCompressingWhiteSpace(
            "CREATE VIEW \"user_view\" SQL SECURITY INVOKER AS SELECT * FROM \"User\""));
    Ddl.Builder ddlBuilder = Ddl.builder();
    ddlBuilder.addView(view);
    Ddl ddl = ddlBuilder.build();
    assertEquals(view, ddl.view("user_view"));
    List<String> statements = ddl.statements();
    assertEquals(1, statements.size());
    assertEquals(
        "CREATE VIEW \"user_view\" SQL SECURITY INVOKER AS SELECT * FROM \"User\"",
        statements.get(0));
    assertNotNull(view.hashCode());
  }

  @Test
  public void changeStreams() {
    Ddl ddl =
        Ddl.builder()
            .createChangeStream("ChangeStreamAll")
            .forClause("FOR ALL")
            .options(
                ImmutableList.of(
                    "retention_period=\"7d\"", "value_capture_type=\"OLD_AND_NEW_VALUES\""))
            .endChangeStream()
            .createChangeStream("ChangeStreamEmpty")
            .endChangeStream()
            .createChangeStream("ChangeStreamTableColumns")
            .forClause("FOR `T1`, `T2`(`c1`, `c2`), `T3`()")
            .endChangeStream()
            .build();
    assertThat(
        ddl.prettyPrint(),
        equalToCompressingWhiteSpace(
            "CREATE CHANGE STREAM `ChangeStreamAll`"
                + " FOR ALL"
                + " OPTIONS (retention_period=\"7d\", value_capture_type=\"OLD_AND_NEW_VALUES\")"
                + " CREATE CHANGE STREAM `ChangeStreamEmpty`"
                + " CREATE CHANGE STREAM `ChangeStreamTableColumns`"
                + " FOR `T1`, `T2`(`c1`, `c2`), `T3`()"));

    List<String> statements = ddl.statements();
    assertEquals(3, statements.size());
    assertThat(
        statements.get(0),
        equalToCompressingWhiteSpace(
            "CREATE CHANGE STREAM `ChangeStreamAll`"
                + " FOR ALL"
                + " OPTIONS (retention_period=\"7d\", value_capture_type=\"OLD_AND_NEW_VALUES\")"));
    assertThat(
        statements.get(1),
        equalToCompressingWhiteSpace(" CREATE CHANGE STREAM `ChangeStreamEmpty`"));
    assertThat(
        statements.get(2),
        equalToCompressingWhiteSpace(
            " CREATE CHANGE STREAM `ChangeStreamTableColumns`"
                + " FOR `T1`, `T2`(`c1`, `c2`), `T3`()"));
    assertNotNull(ddl.hashCode());
  }

  @Test
  public void testDdlEquals() {
    Ddl ddl1 = Ddl.builder(Dialect.GOOGLE_STANDARD_SQL).build();
    Ddl ddl2 = Ddl.builder(Dialect.POSTGRESQL).build();
    assertFalse(ddl1.equals(ddl2));
    Ddl.Builder ddl1Builder =
        Ddl.builder().createTable("Users").column("id").int64().endColumn().endTable();
    ddl1Builder.createTable("Users");
    ddl1 = ddl1Builder.build();
    assertFalse(ddl1.equals(ddl2));
  }

  @Test
  public void testIndexColumnBuilder() {
    IndexColumnsBuilder indexColumnsBuilder = new IndexColumnsBuilder(null, null);
    assertThrows(IllegalArgumentException.class, () -> indexColumnsBuilder.name("name"));
    assertThrows(IllegalArgumentException.class, () -> indexColumnsBuilder.asc());
    assertThrows(IllegalArgumentException.class, () -> indexColumnsBuilder.desc());
    assertThrows(IllegalArgumentException.class, () -> indexColumnsBuilder.storing());
    assertThrows(IllegalArgumentException.class, () -> indexColumnsBuilder.nullsFirst());
    assertThrows(IllegalArgumentException.class, () -> indexColumnsBuilder.nullsLast());

    IndexColumn.Builder indexColumnBuilder = new AutoValue_IndexColumn.Builder();
    assertThrows(NullPointerException.class, () -> indexColumnBuilder.name(null));
    assertThrows(NullPointerException.class, () -> indexColumnBuilder.order(null));
    assertThrows(NullPointerException.class, () -> indexColumnBuilder.dialect(null));
    assertThrows(IllegalStateException.class, () -> indexColumnBuilder.autoBuild());
    IndexColumn indexColumn =
        indexColumnBuilder
            .name("col1")
            .order(Order.ASC)
            .dialect(Dialect.GOOGLE_STANDARD_SQL)
            .autoBuild();
    assertTrue(indexColumn.equals(indexColumn));
    assertFalse(indexColumn.equals(Boolean.TRUE));
    IndexColumn indexColumn1 = IndexColumn.create("col1", Order.ASC);
    assertTrue(indexColumn.equals(indexColumn1));
  }

  @Test
  public void testColumnBuilder() {
    Column.Builder columnBuilder = Column.builder();
    assertThrows(NullPointerException.class, () -> columnBuilder.name(null));
    assertThrows(NullPointerException.class, () -> columnBuilder.type(null));
    assertThrows(NullPointerException.class, () -> columnBuilder.columnOptions(null));
    assertThrows(NullPointerException.class, () -> columnBuilder.dialect(null));
    assertThrows(NullPointerException.class, () -> columnBuilder.name(null));
    assertThrows(NullPointerException.class, () -> columnBuilder.name(null));
    assertThrows(IllegalStateException.class, () -> columnBuilder.autoBuild());
    Column column = Column.builder().name("colName").type(Type.string()).autoBuild();
    assertTrue(column.equals(column));
    assertFalse(column.equals(Boolean.TRUE));
    Column column1 = Column.builder().name("colname").type(Type.bool()).autoBuild();
    assertFalse(column.equals(column1));
    column1 = Column.builder().name("colName").type(Type.bool()).autoBuild();
    assertFalse(column.equals(column1));
    column1 = Column.builder().name("colName").type(Type.string()).size(20).autoBuild();
    assertFalse(column.equals(column1));
    column1 = Column.builder().name("colName").type(Type.string()).notNull().autoBuild();
    assertFalse(column.equals(column1));
    column1 = Column.builder().name("colName").type(Type.string()).isGenerated(true).autoBuild();
    assertFalse(column.equals(column1));
    column1 =
        Column.builder()
            .name("colName")
            .type(Type.string())
            .generationExpression("1+2")
            .autoBuild();
    assertFalse(column.equals(column1));
    column1 =
        Column.builder().name("colName").type(Type.string()).defaultExpression("1+2").autoBuild();
    assertFalse(column.equals(column1));
    column1 = Column.builder().name("colName").type(Type.string()).isStored(true).autoBuild();
    assertFalse(column.equals(column1));
    column1 = Column.builder().name("colName").type(Type.string()).autoBuild();
    assertTrue(column.equals(column1));
  }

  @Test
  public void testTableBuilder() {
    Table.Builder tableBuilder = Table.builder();
    assertThrows(NullPointerException.class, () -> tableBuilder.primaryKeys(null));
    assertThrows(NullPointerException.class, () -> tableBuilder.columns(null));
    assertThrows(NullPointerException.class, () -> tableBuilder.indexes(null));
    assertThrows(NullPointerException.class, () -> tableBuilder.foreignKeys(null));
    assertThrows(NullPointerException.class, () -> tableBuilder.checkConstraints(null));
    assertThrows(NullPointerException.class, () -> tableBuilder.dialect(null));
    assertThrows(IllegalStateException.class, () -> tableBuilder.autoBuild());
    assertThrows(IllegalStateException.class, () -> tableBuilder.columns());
    Ddl.Builder ddlBuilder = Ddl.builder();
    ddlBuilder
        .createTable("Users")
        .column("id")
        .int64()
        .notNull()
        .endColumn()
        .primaryKey()
        .asc("id")
        .end()
        .endTable();
    Table table = ddlBuilder.build().table("Users");
    assertTrue(table.equals(table));
    assertFalse(table.equals(Boolean.TRUE));
    ddlBuilder = Ddl.builder();
    ddlBuilder
        .createTable("Users")
        .column("id")
        .int64()
        .notNull()
        .endColumn()
        .primaryKey()
        .asc("id")
        .end()
        .endTable();
    Table table1 = ddlBuilder.build().table("Users");
    assertTrue(table.equals(table1));
    tableBuilder.columns(ImmutableList.of());
    assertEquals(0, tableBuilder.columns().size());
  }

  @Test
  public void testForeignKeyBuilder() {
    ForeignKey.Builder foreignKeyBuilder = ForeignKey.builder();
    assertThrows(NullPointerException.class, () -> foreignKeyBuilder.name(null));
    assertThrows(NullPointerException.class, () -> foreignKeyBuilder.table(null));
    assertThrows(NullPointerException.class, () -> foreignKeyBuilder.referencedTable(null));
    assertThrows(NullPointerException.class, () -> foreignKeyBuilder.dialect(null));
    assertThrows(IllegalStateException.class, () -> foreignKeyBuilder.build());
    ForeignKey foreignKey =
        foreignKeyBuilder.name("fk").table("table1").referencedTable("table2").build();
    assertTrue(foreignKey.equals(foreignKey));
    assertFalse(foreignKey.equals(Boolean.TRUE));
    ForeignKey foreignKey1 =
        ForeignKey.builder().name("fk").table("table1").referencedTable("table2").build();
    assertTrue(foreignKey.equals(foreignKey1));
  }

  @Test
  public void testCheckConstraintBuilder() {
    CheckConstraint.Builder checkConstraintBuilder = CheckConstraint.builder();
    assertThrows(NullPointerException.class, () -> checkConstraintBuilder.name(null));
    assertThrows(NullPointerException.class, () -> checkConstraintBuilder.expression(null));
    assertThrows(NullPointerException.class, () -> checkConstraintBuilder.dialect(null));
    assertThrows(IllegalStateException.class, () -> checkConstraintBuilder.build());
    CheckConstraint checkConstraint = checkConstraintBuilder.name("ck").expression("1<2").build();
    assertTrue(checkConstraint.equals(checkConstraint));
    assertFalse(checkConstraint.equals(Boolean.TRUE));
    CheckConstraint checkConstraint1 = checkConstraintBuilder.name("ck").expression("1<2").build();
    assertTrue(checkConstraint.equals(checkConstraint1));
  }
}


text:
import { Component } from 'vidom';
import Focusable from '../Focusable';
import bem from '../../utils/bem';
import keyCodes from '../../utils/keyCodes';
import noOp from '../../utils/noOp';

const b = bem('Link');

export default class Link extends Component {
    onInit() {
        this._onFocus = this._onFocus.bind(this);
        this._onBlur = this._onBlur.bind(this);
        this._onMouseClick = this._onMouseClick.bind(this);
        this._onKeyDown = this._onKeyDown.bind(this);

        this.setState({ focused : this.attrs.focused });
    }

    onAttrsReceive() {
        const { focused } = this.attrs;

        if(typeof focused !== 'undefined' && focused !== this.state.focused) {
            this.setState({ focused });
        }
    }

    onRender() {
        const {
                attrs : {
                    theme,
                    size,
                    view,
                    title,
                    disabled,
                    url,
                    target,
                    mix
                },
                state : { focused }
            } = this,
            focusableAttrs = {},
            domAttrs = {
                role : 'link',
                'aria-disabled' : disabled,
                title,
                target,
                className : b({
                    theme : theme || this.context.theme,
                    size,
                    view,
                    disabled,
                    focused
                })
            };

        if(mix) {
            domAttrs.className += ' ' + mix;
        }

        if(!disabled) {
            focusableAttrs.focused = focused;
            focusableAttrs.onFocus = this._onFocus;
            focusableAttrs.onBlur = this._onBlur;

            domAttrs.href = url;
            domAttrs.onClick = this._onMouseClick;

            if(focused) {
                domAttrs.onKeyDown = this._onKeyDown;
            }
        }

        return (
            <Focusable { ...focusableAttrs }>
                <a { ...domAttrs }>
                    { this.children }
                </a>
            </Focusable>
        );
    }

    _onFocus() {
        this.attrs.onFocusChange(true);
        this.setState({ focused : true });
    }

    _onBlur() {
        this.attrs.onFocusChange(false);
        this.setState({ focused : false });
    }

    _onMouseClick(e) {
        if(!e.nativeEvent.button) {
            this._onClick(e);
        }
    }

    _onClick(e) {
        if(this.attrs.pseudo) {
            e.preventDefault();
        }

        this.attrs.onClick(e);
    }

    _onKeyDown(e) {
        if(e.nativeEvent.keyCode === keyCodes.SPACE) {
            const { onClick, pseudo, url } = this.attrs;

            onClick(e);

            if(!pseudo) {
                document.location = url;
            }
        }
    }
}

Link.defaultAttrs = {
    onClick : noOp,
    onFocusChange : noOp
};


text:
from os import environ as env
from glob import glob

import datetime
import dropbox

FILENAME = 'build/libs/WhoWas.jar'

def main():
    client = dropbox.client.DropboxClient(env.get('DROPBOX_ACCESS_TOKEN'))
    base = FILENAME.split('/')[2].split('.jar')[0]
    date = datetime.datetime.now().strftime("%Y-%m-%d")
    build_id = env['TRAVIS_JOB_NUMBER']

    with open(FILENAME) as f:
        client.put_file('/' + base + '-' + date + '-' + build_id, f, overwrite=True)
    print("Successfully uploaded latest build to Dropbox")

if __name__ == "__main__":
    main()


text:
"""A tool for cost analysis."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from google.protobuf import text_format

from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python.grappler import cost_analyzer
from tensorflow.python.grappler import tf_optimizer
from tensorflow.python.platform import app
from tensorflow.python.platform import gfile

def main(_):
  with gfile.GFile(FLAGS.input) as input_file:
    metagraph = meta_graph_pb2.MetaGraphDef()
    metagraph.ParseFromString(input_file.read())

  if FLAGS.rewriter_config is not None:
    rewriter_config = rewriter_config_pb2.RewriterConfig()
    text_format.Merge(FLAGS.rewriter_config, rewriter_config)
    optimized_graph = tf_optimizer.OptimizeGraph(rewriter_config, metagraph)
    metagraph.graph_def.CopyFrom(optimized_graph)

  report = cost_analyzer.GenerateCostReport(metagraph, FLAGS.per_node_report)
  print(report)

if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.add_argument(
      "--input", type=str, default=None, help="Input .meta file path.")
  parser.add_argument(
      "--rewriter_config",
      type=str,
      default=None,
      help="Configuration for the grappler optimizers, described as a "
      "RewriterConfig protocol buffer. Usage example 1: "
      "--rewriter_config='optimize_tensor_layout: true "
      "disable_model_pruning: true'. Usage example 2: "
      "--rewriter_config='optimizers: \"constfold\" optimizers: \"layout\"'")
  parser.add_argument(
      "--per_node_report",
      action="store_true",
      help="Generate per-node report. By default the report contains stats "
      "aggregated on a per op type basis, per_node_report adds results "
      "for each individual node to the report.")
  FLAGS, unparsed = parser.parse_known_args()
  app.run(main=main, argv=[sys.argv[0]] + unparsed)


text: {{ global_announcement_text }}


text:
exports.names = ['lockskip'];
exports.hidden = true;
exports.enabled = true;
exports.matchStart = false;
exports.cd_all = 3;
exports.cd_user = 3;
exports.cd_manager = 3;
exports.min_role = PERMISSIONS.BOUNCER;
exports.handler = function (data) {
    var media = bot.getMedia();
    var dj = bot.getDJ();

    console.info('[LOCKSKIP] ' + data.from.username + ' lockskipped ' + dj.username);

    var userData = {
        type: 'lockskip',
        details: 'Skipped by ' + data.from.username,
        user_id: dj.id,
        mod_user_id: data.from.id
    };
    Karma.create(userData);

    modMessage(data, 'Lockskipped the current song.');
    lockskip(dj);
};


text:
package localpage;

import org.openqa.selenium.WebDriver;

import java.net.URL;

public class LocalPage {
    private final WebDriver driver;
    private final URL url = getClass().getClassLoader().getResource("checkout/index.html");

    public LocalPage(WebDriver driver) {
        this.driver = driver;
    }

    protected LocalPageElements elements() {
        return new LocalPageElements(driver);
    }

    public LocalPageAssertions assertions() {
        return new LocalPageAssertions(driver);
    }

    public void navigate() {
        driver.navigate().to(url);
    }

    public void fillInfo(ClientInfo clientInfo) {
        elements().firstName().sendKeys(clientInfo.getFirstName());
        elements().lastName().sendKeys(clientInfo.getLastName());
        elements().username().sendKeys(clientInfo.getUsername());
        elements().email().sendKeys(clientInfo.getEmail());
        elements().address1().sendKeys(clientInfo.getAddress1());
        elements().address2().sendKeys(clientInfo.getAddress2());
        elements().country().selectByIndex(clientInfo.getCountry());
        elements().state().selectByIndex(clientInfo.getState());
        elements().zip().sendKeys(clientInfo.getZip());
        elements().cardName().sendKeys(clientInfo.getCardName());
        elements().cardNumber().sendKeys(clientInfo.getCardNumber());
        elements().cardExpiration().sendKeys(clientInfo.getCardExpiration());
        elements().cardCVV().sendKeys(clientInfo.getCardCVV());

        elements().submitButton().click();
    }
}


text:
<?php
/* Teams Test cases generated on: 2010-03-27 06:03:29 : 1269639749*/
App::import('Controller', 'Teams');

class TestTeamsController extends TeamsController {
	var $autoRender = false;

	function redirect($url, $status = null, $exit = true) {
		$this->redirectUrl = $url;
	}
}

class TeamsControllerTestCase extends CakeTestCase {
	var $fixtures = array('app.team', 'app.teammember', 'app.user', 'app.task', 'app.sprint', 'app.story', 'app.priority', 'app.remaining_time');

	function startTest() {
		$this->Teams =& new TestTeamsController();
		$this->Teams->constructClasses();
	}

	function endTest() {
		unset($this->Teams);
		ClassRegistry::flush();
	}

	function testIndex() {

	}

	function testView() {

	}

	function testAdd() {

	}

	function testEdit() {

	}

	function testDelete() {

	}

	function testAdminIndex() {

	}

	function testAdminView() {

	}

	function testAdminAdd() {

	}

	function testAdminEdit() {

	}

	function testAdminDelete() {

	}

}
?>