text:
package org.nanohttpd.junit.router;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.nanohttpd.protocols.http.response.Status;
import org.nanohttpd.router.RouterNanoHTTPD;
import org.nanohttpd.router.RouterNanoHTTPD.DefaultRoutePrioritizer;
import org.nanohttpd.router.RouterNanoHTTPD.Error404UriHandler;
import org.nanohttpd.router.RouterNanoHTTPD.GeneralHandler;
import org.nanohttpd.router.RouterNanoHTTPD.IndexHandler;
import org.nanohttpd.router.RouterNanoHTTPD.InsertionOrderRoutePrioritizer;
import org.nanohttpd.router.RouterNanoHTTPD.NotImplementedHandler;
import org.nanohttpd.router.RouterNanoHTTPD.ProvidedPriorityRoutePrioritizer;
import org.nanohttpd.router.RouterNanoHTTPD.StaticPageHandler;
import org.nanohttpd.router.RouterNanoHTTPD.UriResource;
import org.nanohttpd.router.RouterNanoHTTPD.UriResponder;
import org.nanohttpd.router.RouterNanoHTTPD.UriRouter;

public class TestNanolets {

    private static PipedOutputStream stdIn;

    private static Thread serverStartThread;

    @BeforeClass
    public static void setUp() throws Exception {
        stdIn = new PipedOutputStream();
        System.setIn(new PipedInputStream(stdIn));
        serverStartThread = new Thread(new Runnable() {

            @Override
            public void run() {
                String[] args = {};
                AppNanolets.main(args);
            }
        });
        serverStartThread.start();
        // give the server some tine to start.
        Thread.sleep(200);
    }

    public static void main(String[] args) {
        {
            String uri = "def";
            Pattern.compile("([A-Za-z0-9\\-\\._~:/?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=]+)");
            Pattern URI_PATTERN = Pattern.compile("([A-Za-z0-9\\-\\._~:/?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=]+)");
            System.out.println(URI_PATTERN.matcher(uri).matches());
        }

        String uri = "photos/abc/def";
        Pattern URI_PATTERN = Pattern.compile("photos/([A-Za-z0-9\\-\\._~:/?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=]+)/([A-Za-z0-9\\-\\._~:/?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=]+)");
        Matcher matcher = URI_PATTERN.matcher(uri);
        System.out.println("--------------->" + "/" + uri);
        while (matcher.matches()) {

            System.out.println(matcher.group());
        }
        // for (int index = 0; index < matcher.groupCount(); index++) {
        // System.out.println(matcher.group());
        // }
    }

    @Test
    public void doSomeBasicMethodTest() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet("http://localhost:9090/user/blabla");
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals(
                "User handler. Method: GET

Uri parameters:

 Param: id Value: blabla

Query parameters:
", string);
        response.close();

        HttpPost httppost = new HttpPost("http://localhost:9090/user/blabla");
        response = httpclient.execute(httppost);
        entity = response.getEntity();
        string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals(
                "User handler. Method: POST

Uri parameters:

 Param: id Value: blabla

Query parameters:
", string);
        response.close();

        HttpPut httpgput = new HttpPut("http://localhost:9090/user/blabla");
        response = httpclient.execute(httpgput);
        entity = response.getEntity();
        string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals(
                "User handler. Method: PUT

Uri parameters:

 Param: id Value: blabla

Query parameters:
", string);
        response.close();

        HttpDelete httpdelete = new HttpDelete("http://localhost:9090/user/blabla");
        response = httpclient.execute(httpdelete);
        entity = response.getEntity();
        string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals(
                "User handler. Method: DELETE

Uri parameters:

 Param: id Value: blabla

Query parameters:
", string);
        response.close();
    }

    @Test
    public void doEncodedRequest() throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet("http://localhost:9090/general/param%201/param%202");
        CloseableHttpResponse response = httpclient.execute(httpget);
        Assert.assertEquals(Status.OK.getRequestStatus(), response.getStatusLine().getStatusCode());
    }

    @Test
    public void doNonRouterRequest() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet("http://localhost:9090/test");
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("Return: java.lang.String.toString() -> ", string);
        response.close();
    }

    @Test
    public void doExceptionRequest() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet("http://localhost:9090/interface");
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("Error: java.lang.InstantiationException : org.nanohttpd.router.RouterNanoHTTPD$UriResponder", string);
        response.close();
    }

    @Test
    public void doDeletedRoute() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet("http://localhost:9090/toBeDeleted");
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
Error 404: the requested page doesn't exist.
", string);
        response.close();
    }

    @Test
    public void doUriSelection1() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet("http://localhost:9090/user/help");
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
Url: /user/help

no params in url

", string);
        response.close();
    }

    @Test
    public void doStreamOfData() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet("http://localhost:9090/stream");
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("a stream of data ;-)", string);
        response.close();
    }

    @Test(expected = IllegalStateException.class)
    public void illegalMethod1() throws Exception {
        new AppNanolets.UserHandler().getData();
    }

    @Test(expected = IllegalStateException.class)
    public void illegalMethod2() throws Exception {
        new RouterNanoHTTPD.GeneralHandler().getText();
    }

    @Test(expected = IllegalStateException.class)
    public void illegalMethod3() throws Exception {
        new RouterNanoHTTPD.StaticPageHandler().getText();
    }

    @Test(expected = IllegalStateException.class)
    public void illegalMethod4() throws Exception {
        new RouterNanoHTTPD.StaticPageHandler().getMimeType();
    }

    @Test(expected = ClassCastException.class)
    public void checkIniParameter1() throws Exception {
        new RouterNanoHTTPD.UriResource("browse", 100, null, "init").initParameter(String.class);
        new RouterNanoHTTPD.UriResource("browse", 100, null, "init").initParameter(Integer.class);
    }

    @Test
    public void checkIniParameter2() throws Exception {
        Assert.assertEquals("init", new RouterNanoHTTPD.UriResource("browse", 100, null, "init").initParameter(String.class));
        Assert.assertNull(new RouterNanoHTTPD.UriResource("browse", 100, null).initParameter(String.class));
    }

    @Test
    public void doGeneralParams() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet("http://localhost:9090/general/value1/value2?param3=value3&param4=value4");

        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
Url: /general/value1/value2

Param 'param3' = value3

Param 'param4' = value4
", string);
        response.close();
    }

    @Test
    public void doIndexHandler() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet("http://localhost:9090/index.html");
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
Hello world!
", string);
        response.close();
    }

    @Test
    public void doMissingHandler() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet httpget = new HttpGet("http://localhost:9090/photos/abc/def");
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
The uri is mapped in the router, but no handler is specified.
 Status: Not implemented!
", string);
        response.close();
    }

    @Test
    public void uriToString() throws Exception {
        Assert.assertEquals(//
                "UrlResource{uri='photos/:customer_id/:photo_id', urlParts=[customer_id, photo_id]}",//
                new UriResource("/photos/:customer_id/:photo_id", 100, GeneralHandler.class).toString());
    }

    @Test
    public void doOtherMethod() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpTrace httphead = new HttpTrace("http://localhost:9090/index.html");
        CloseableHttpResponse response = httpclient.execute(httphead);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
Hello world!
", string);
        response.close();
    }

    @Test
    public void normalize() throws Exception {
        Assert.assertNull(RouterNanoHTTPD.normalizeUri(null));
        Assert.assertEquals("", RouterNanoHTTPD.normalizeUri("/"));
        Assert.assertEquals("xxx/yyy", RouterNanoHTTPD.normalizeUri("/xxx/yyy"));
        Assert.assertEquals("xxx/yyy", RouterNanoHTTPD.normalizeUri("/xxx/yyy/"));
    }

    private byte[] readContents(HttpEntity entity) throws IOException {
        InputStream instream = entity.getContent();
        return readContents(instream);
    }

    private byte[] readContents(InputStream instream) throws IOException {
        byte[] bytes;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            byte[] buffer = new byte[1024];
            int count;
            while ((count = instream.read(buffer)) >= 0) {
                out.write(buffer, 0, count);
            }
            bytes = out.toByteArray();
        } finally {
            instream.close();
        }
        return bytes;
    }

    @Test
    public void staticFiles() throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpTrace httphead = new HttpTrace("http://localhost:9090/browse/blabla.html");
        CloseableHttpResponse response = httpclient.execute(httphead);
        HttpEntity entity = response.getEntity();
        String string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
just a page
", string);
        response.close();

        httphead = new HttpTrace("http://localhost:9090/browse/dir/blabla.html");
        response = httpclient.execute(httphead);
        entity = response.getEntity();
        string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
just an other page
", string);
        response.close();

        httphead = new HttpTrace("http://localhost:9090/browse/dir/nanohttpd_logo.png");
        response = httpclient.execute(httphead);
        entity = response.getEntity();
        Assert.assertEquals("image/png", entity.getContentType().getValue());
        response.close();

        httphead = new HttpTrace("http://localhost:9090/browse/dir/xxx.html");
        response = httpclient.execute(httphead);
        entity = response.getEntity();
        string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
Error 404: the requested page doesn't exist.
", string);
        response.close();

        httphead = new HttpTrace("http://localhost:9090/browse/dir/");
        response = httpclient.execute(httphead);
        entity = response.getEntity();
        string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("
just an index page
", string);
        response.close();

        httphead = new HttpTrace("http://localhost:9090/browse/exception.html");
        response = httpclient.execute(httphead);
        Assert.assertEquals(Status.REQUEST_TIMEOUT.getRequestStatus(), response.getStatusLine().getStatusCode());
        entity = response.getEntity();
        string = new String(readContents(entity), "UTF-8");
        Assert.assertEquals("", string);
        response.close();
    }

    @AfterClass
    public static void tearDown() throws Exception {
        stdIn.write("\n\n".getBytes());
        serverStartThread.join(2000);
        Assert.assertFalse(serverStartThread.isAlive());
    }

    @Test
    public void testGeneralHandlerGetStatus() {
        Assert.assertEquals("GeneralHandler#getStatus should return OK status", Status.OK, new RouterNanoHTTPD.GeneralHandler().getStatus());
    }

    @Test
    public void testStaticPageHandlerGetStatus() {
        Assert.assertEquals("StaticPageHandler#getStatus should return OK status", Status.OK, new RouterNanoHTTPD.StaticPageHandler().getStatus());
    }

    @Test
    public void testError404UriHandlerGetStatus() {
        Assert.assertEquals("Error404UriHandler#getStatus should return NOT_FOUND status", Status.NOT_FOUND, new RouterNanoHTTPD.Error404UriHandler().getStatus());
    }

    @Test
    public void testError404UriHandlerGetMimeType() {
        Assert.assertEquals("Error404UriHandler mime type should be text/html", "text/html", new RouterNanoHTTPD.Error404UriHandler().getMimeType());
    }

    @Test
    public void testNotImplementedHandlerGetStatus() {
        Assert.assertEquals("NotImplementedHandler#getStatus should return OK status", Status.OK, new RouterNanoHTTPD.NotImplementedHandler().getStatus());
    }

    @Test
    public void testIndexHandlerGetStatus() {
        Assert.assertEquals("IndexHandler#getStatus should return OK status", Status.OK, new RouterNanoHTTPD.IndexHandler().getStatus());
    }

    @Test
    public void testIndexHandlerGetMimeType() {
        Assert.assertEquals("IndexHandler mime type should be text/html", "text/html", new RouterNanoHTTPD.IndexHandler().getMimeType());
    }

    @Test
    public void testNotImplementedHandlerGetMimeType() {
        Assert.assertEquals("NotImplementedHandler mime type should be text/html", "text/html", new RouterNanoHTTPD.NotImplementedHandler().getMimeType());
    }

    @Test
    public void testBaseRoutePrioritizerAddNullRoute() {
        DefaultRoutePrioritizer routePrioritizer = new DefaultRoutePrioritizer();
        routePrioritizer.addRoute(null, 100, null);
        Assert.assertEquals(0, routePrioritizer.getPrioritizedRoutes().size());
    }

    @Test
    public void testInsertionOrderRoutePrioritizer() throws IOException {
        InsertionOrderRoutePrioritizer routePrioritizer = new InsertionOrderRoutePrioritizer();

        Class<?> handler1 = String.class;
        Class<?> handler2 = Boolean.class;
        Class<?> handler3 = Long.class;

        ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
        classes.add(handler1);
        classes.add(handler2);
        classes.add(handler3);

        routePrioritizer.addRoute("/user", 100, handler1);
        routePrioritizer.addRoute("/user", 100, handler2);
        routePrioritizer.addRoute("/user", 100, handler3);
        List<UriResource> prioritizedResources = new ArrayList<UriResource>();
        prioritizedResources.addAll(routePrioritizer.getPrioritizedRoutes());

        for (int i = 0; i < classes.size(); i++) {
            Class<?> handler = classes.get(i);
            UriResource resource = prioritizedResources.get(i);

            InputStream inputStream = resource.process(null, null).getData();
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            String message = new String(bytes);

            Assert.assertTrue(message.contains(handler.getCanonicalName()));

        }
    }

    @Test
    public void testProvidedPriorityRoutePrioritizerNullUri() {
        ProvidedPriorityRoutePrioritizer routePrioritizer = new ProvidedPriorityRoutePrioritizer();
        Assert.assertEquals(0, routePrioritizer.getPrioritizedRoutes().size());
        routePrioritizer.addRoute(null, 100, null);
        Assert.assertEquals(0, routePrioritizer.getPrioritizedRoutes().size());
    }

    @Test
    public void testProvidedPriorityRoutePrioritizerNullHandler() {
        ProvidedPriorityRoutePrioritizer routePrioritizer = new ProvidedPriorityRoutePrioritizer();
        Assert.assertEquals(0, routePrioritizer.getPrioritizedRoutes().size());
        routePrioritizer.addRoute("/help", 100, null);
        Assert.assertEquals(1, routePrioritizer.getPrioritizedRoutes().size());
    }

    @Test
    public void testProvidedPriorityRoutePrioritizer() throws IOException {
        ProvidedPriorityRoutePrioritizer routePrioritizer = new ProvidedPriorityRoutePrioritizer();

        Class<?> handler1 = String.class;
        Class<?> handler2 = Boolean.class;
        Class<?> handler3 = Long.class;

        ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
        classes.add(handler2);
        classes.add(handler1);
        classes.add(handler3);

        routePrioritizer.addRoute("/user", 101, handler1);
        routePrioritizer.addRoute("/user", 100, handler2);
        routePrioritizer.addRoute("/user", 102, handler3);
        List<UriResource> prioritizedResources = new ArrayList<UriResource>();
        prioritizedResources.addAll(routePrioritizer.getPrioritizedRoutes());

        for (int i = 0; i < classes.size(); i++) {
            Class<?> handler = classes.get(i);
            UriResource resource = prioritizedResources.get(i);

            InputStream inputStream = resource.process(null, null).getData();
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            String message = new String(bytes);

            Assert.assertTrue(message.contains(handler.getCanonicalName()));
        }
    }

    @Test
    public void testUriResourceComparator() {
        UriResource r1 = new UriResource("uri", null);
        r1.setPriority(100);
        Assert.assertTrue(r1.compareTo(null) >= 1);

        UriResource r2 = new UriResource("uri", null);
        r2.setPriority(100);
        Assert.assertEquals(0, r1.compareTo(r2));

        r2.setPriority(99);
        Assert.assertTrue(r1.compareTo(r2) >= 1);

        r2.setPriority(101);
        Assert.assertTrue(r1.compareTo(r2) <= 1);
    }

    @Test
    public void testUriResourceMatch() {
        UriResource resource = new RouterNanoHTTPD.UriResource("browse", 100, null, "init");
        Assert.assertNull("UriResource should not match incorrect URL, and thus, should not return a URI parameter map", resource.match("/xyz/pqr/"));
        Assert.assertNotNull("UriResource should match the correct URL, and thus, should return a URI parameter map", resource.match("browse"));
    }

    @Test
    public void testRoutePrioritizerRemoveRouteNoRouteMatches() {
        DefaultRoutePrioritizer prioritizer = new DefaultRoutePrioritizer();
        prioritizer.addRoute("/world", 100, NotImplementedHandler.class);
        prioritizer.removeRoute("/hello");

        Assert.assertEquals(1, prioritizer.getPrioritizedRoutes().size());
    }

    @Test
    public void testHandlerSetters() throws Exception {
        final UriResponder notFoundHandler = new GeneralHandler() {
        };
        final UriResponder notImplementedHandler = new GeneralHandler() {
        };

        TestRouter router = new TestRouter();

        RouterNanoHTTPD routerNanoHttpd = new RouterNanoHTTPD(9999);

        Field routerField = RouterNanoHTTPD.class.getDeclaredField("router");
        routerField.setAccessible(true);
        routerField.set(routerNanoHttpd, router);

        routerNanoHttpd.setNotFoundHandler(notFoundHandler.getClass());
        routerNanoHttpd.setNotImplementedHandler(notImplementedHandler.getClass());

        Assert.assertEquals(notFoundHandler.getClass(), router.notFoundHandlerClass);
        Assert.assertEquals(notImplementedHandler.getClass(), router.notImplementedHandlerClass);
    }

    private static final class TestRouter extends UriRouter {

        private Class<?> notFoundHandlerClass;

        private Class<?> notImplementedHandlerClass;

        @Override
        public void setNotFoundHandler(Class<?> handler) {
            notFoundHandlerClass = handler;
        }

        @Override
        public void setNotImplemented(Class<?> handler) {
            notImplementedHandlerClass = handler;
        }
    }
}


text:
Agouti
======

[![Build Status](https://api.travis-ci.org/sclevine/agouti.png?branch=master)](http://travis-ci.org/sclevine/agouti)
[![GoDoc](https://godoc.org/github.com/sclevine/agouti?status.svg)](https://godoc.org/github.com/sclevine/agouti)

**NOTE: Agouti is no longer actively maintained. This was one of my earliest Go projects, and I am no longer happy with the API design. I recommend selecting an alternative WebDriver client for Go.**

Agouti is a library for writing browser-based acceptance tests in Google Go. It provides [Gomega](https://github.com/onsi/gomega) matchers and plays nicely with [Ginkgo](https://github.com/onsi/ginkgo) or [Spec](https://github.com/sclevine/spec). See [agouti.org](http://agouti.org) and the [GoDoc](https://godoc.org/github.com/sclevine/agouti) for documentation. Have questions? Check out the [Agouti mailing list](https://groups.google.com/d/forum/agouti) or the #agouti IRC channel on Freenode.

The [integration tests](https://github.com/sclevine/agouti/blob/master/internal/integration/) are a great place to see everything in action and get started quickly!

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Net;

namespace BAMCIS.Infoblox.Core.InfobloxStructs
{
    public class extserver
    {
        private string _address;
        private string _name;
        private string _tsig_key;
        private string _tsig_key_alg;
        private string _tsig_key_name;

        public string address
        {
            get
            {
                return this._address;
            }
            set
            {
                IPAddress ip;
                if (IPAddress.TryParse(value, out ip))
                {
                    this._address = ip.ToString();
                }
                else
                {
                    throw new ArgumentException("The address must be a valid IPv4 or IPv6 address.");
                }

            }
        }
        public string name
        {
            get
            {
                return this._name;
            }
            set
            {
                this._name = value.TrimValue();
            }
        }
        public bool shared_with_ms_parent_delegation { get; set; }
        public bool stealth { get; set; }
        public string tsig_key
        {
            get
            {
                return this._tsig_key;
            }
            set
            {
                this._tsig_key = value.TrimValue();
            }
        }
        public string tsig_key_alg
        {
            get
            {
                return this._tsig_key_alg;
            }
            set
            {
                if (!String.IsNullOrEmpty(value) && ( value.Equals("HMAC-MD5") || value.Equals("HMAC-SHA256")))
                {
                    this._tsig_key_alg = value;
                }
                else
                {
                    throw new ArgumentException("The TSIG key algorithm must be valid.");
                }
            }
        }
        public string tsig_key_name
        {
            get
            {
                return this._tsig_key_name;
            }
            set
            {
                this._tsig_key_name = value.TrimValue();
            }
        }

        public bool use_tsig_key_name { get; set; }

        public extserver()
        {
            this.stealth = false;
            this.tsig_key_alg = "HMAC-MD5";
            this.use_tsig_key_name = false;
        }
    }
}


text:
package org.synyx.minos.i18n.service;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.synyx.messagesource.InitializableMessageSource;
import org.synyx.messagesource.MessageProvider;
import org.synyx.minos.i18n.importer.MessageImporter;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class MessageTransferServiceImplUnitTest {

    private MessageTransferServiceImpl messageTransferService;

    @Mock
    private MessageImporter importer;

    @Mock
    private MessageProvider messageProvider;

    @Mock
    private InitializableMessageSource messageSource;

    private List<InitializableMessageSource> mockMessageSources;

    @Before
    public void setUp() {
        mockMessageSources = new ArrayList<InitializableMessageSource>();
        mockMessageSources.add(messageSource);

        messageTransferService = new MessageTransferServiceImpl(importer, messageProvider);
        messageTransferService.setMessageSources(mockMessageSources);
    }

    @Test
    public void testExportMessages() {
        OutputStream outputStream = mock(OutputStream.class);

        messageTransferService.exportMessages(outputStream);
    }

    @Test
    public void testImportMessages() {
        messageTransferService.importMessages();

        verify(messageSource, atLeastOnce()).initialize();
        verify(importer, atLeastOnce()).importMessages();
    }

    @Test
    public void testInitializeMessageSources() {
        messageTransferService.initializeMessageSources();

        verify(messageSource, atLeastOnce()).initialize();
    }

    @Test
    public void testMessageSources() {
        Assert.assertEquals(mockMessageSources, messageTransferService.getMessageSources());
    }
}


text:
 $Id$

 Copyright © 2007-2013 the VideoLAN team

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]

-- Helper function to get a parameter's value in a URL
function get_url_param( url, name )
    local _, _, res = string.find( url, "[&?]"..name.."=([^&]*)" )
    return res
end

function get_arturl()
    local iurl = get_url_param( vlc.path, "iurl" )
    if iurl then
        return iurl
    end
    local video_id = get_url_param( vlc.path, "v" )
    if not video_id then
        return nil
    end
    return "http://img.youtube.com/vi/"..video_id.."/default.jpg"
end

function get_prefres()
    local prefres = -1
    if vlc.var and vlc.var.inherit then
        prefres = vlc.var.inherit(nil, "preferred-resolution")
        if prefres == nil then
            prefres = -1
        end
    end
    return prefres
end

-- Pick the most suited format available
function get_fmt( fmt_list )
    local prefres = get_prefres()
    if prefres < 0 then
        return nil
    end

    local fmt = nil
    for itag,height in string.gmatch( fmt_list, "(%d+)/%d+x(%d+)/[^,]+" ) do
        -- Apparently formats are listed in quality
        -- order, so we take the first one that works,
        -- or fallback to the lowest quality
        fmt = itag
        if tonumber(height) <= prefres then
            break
        end
    end
    return fmt
end

-- Descramble the URL signature using the javascript code that does that
-- in the web page
function js_descramble( sig, js_url )
    -- Fetch javascript code
    local js = vlc.stream( js_url )
    if not js then
        return sig
    end
    local lines = {}

    -- Look for the descrambler function's name
    local descrambler = nil
    while not descrambler do
        local line = js:readline()
        if not line then
            vlc.msg.err( "Couldn't process youtube video URL, please check for updates to this script" )
            return sig
        end
        -- Buffer lines for later, so we don't have to make a second
        -- HTTP request later
        table.insert( lines, line )
        -- c&&(b.signature=ij(c));
        descrambler = string.match( line, "%.signature=(.-)%(" )
    end

    -- Fetch the code of the descrambler function. Example:
    -- function ij(a){a=a.split("");a=a.reverse();a=jj(a,12);a=jj(a,32);a=a.reverse();a=jj(a,34);a=a.slice(3);a=jj(a,35);a=jj(a,42);a=a.slice(2);return a.join("")}
    local rules = nil
    while not rules do
        local line
        if #lines > 0 then
            line = table.remove( lines )
        else
            line = js:readline()
            if not line then
                vlc.msg.err( "Couldn't process youtube video URL, please check for updates to this script" )
                return sig
            end
        end
        rules = string.match( line, "function "..descrambler.."%([^)]*%){(.-)}" )
    end

    -- Parse descrambling rules one by one and apply them on the
    -- signature as we go
    for rule in string.gmatch( rules, "[^;]+" ) do
        -- a=a.reverse();
        if string.match( rule, "%.reverse%(" ) then
            sig = string.reverse( sig )
        else

        -- a=a.slice(3);
        local len = string.match( rule, "%.slice%((%d+)%)" )
        if len then
            sig = string.sub( sig, len + 1 )
        else

        -- a=jj(a,32);
        -- This is known to be a function swapping the first and nth
        -- characters:
        -- function jj(a,b){var c=a[0];a[0]=a[b%a.length];a[b]=c;return a}
        local idx = string.match( rule, "=..%([^,]+,(%d+)%)" )
        -- This swapping function may also appear inlined:
        -- var b=a[0];a[0]=a[59%a.length];a[59]=b;
        -- In that case we only catch one of the three rules.
        if not idx then
            idx = string.match( rule, ".%[(%d+)%]=." )
        end
        if idx then
            idx = tonumber( idx )
            if not idx then idx = 0 end
            if idx > 1 then
                sig = string.gsub( sig, "^(.)("..string.rep( ".", idx - 1 )..")(.)(.*)$", "%3%2%1%4" )
            elseif idx == 1 then
                sig = string.gsub( sig, "^(.)(.)", "%2%1" )
            end
        end end end

        -- Simply ignore other statements, in particular initial split
        -- and final join and return statements
    end
    return sig
end

function descramble81( sig )
    sig = string.reverse( sig )
    local s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13 =
        string.match( sig, "(.)(.......................)(.)(..............)(.)(......)(.)(....)(.)(...................)(.)(........)(.)" )
    return s3..s2..s5..s4..s1..s6..s13..s8..s7..s10..s9..s12..s11
end

local descramblers = {
                       --[81] = descramble81
                     }

function descramble( sig, js_url )
    vlc.msg.dbg( "Found "..string.len( sig ).."-character scrambled signature for youtube video URL, attempting to descramble... " )
    if js_url then
        sig = js_descramble( sig, js_url )
    else
        local descrambler = descramblers[string.len( sig )]
        if descrambler then
            sig = descrambler( sig )
        else
            vlc.msg.err( "Couldn't process youtube video URL, please check for updates to this script" )
        end
    end
    return sig
end

-- Parse and pick our video URL
function pick_url( url_map, fmt, js_url )
    local path = nil
    for stream in string.gmatch( url_map, "[^,]+" ) do
        -- Apparently formats are listed in quality order,
        -- so we can afford to simply take the first one
        local itag = string.match( stream, "itag=(%d+)" )
        if not fmt or not itag or tonumber( itag ) == tonumber( fmt ) then
            local url = string.match( stream, "url=([^&,]+)" )
            if url then
                url = vlc.strings.decode_uri( url )

                local sig = string.match( stream, "sig=([^&,]+)" )
                if not sig then
                    -- Scrambled signature
                    sig = string.match( stream, "s=([^&,]+)" )
                    if sig then
                        sig = descramble( sig, js_url )
                    end
                end
                local signature = ""
                if sig then
                    signature = "&signature="..sig
                end

                path = url..signature
                break
            end
        end
    end
    return path
end

-- Probe function.
function probe()
    if vlc.access ~= "http" and vlc.access ~= "https" then
        return false
    end
    youtube_site = string.match( string.sub( vlc.path, 1, 8 ), "youtube" )
    if not youtube_site then
        -- FIXME we should be using a builtin list of known youtube websites
        -- like "fr.youtube.com", "uk.youtube.com" etc..
        youtube_site = string.find( vlc.path, ".youtube.com" )
        if youtube_site == nil then
            return false
        end
    end
    return (  string.match( vlc.path, "/watch%?" ) -- the html page
            or string.match( vlc.path, "/get_video_info%?" ) -- info API
            or string.match( vlc.path, "/v/" ) -- video in swf player
            or string.match( vlc.path, "/player2.swf" ) ) -- another player url
end

-- Parse function.
function parse()
    if string.match( vlc.path, "/watch%?" )
    then -- This is the HTML page's URL
        -- fmt is the format of the video
        -- (cf. http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs)
        fmt = get_url_param( vlc.path, "fmt" )
        while true do
            -- Try to find the video's title
            line = vlc.readline()
            if not line then break end
            if string.match( line, "<meta name=\"title\"" ) then
                _,_,name = string.find( line, "content=\"(.-)\"" )
                name = vlc.strings.resolve_xml_special_chars( name )
                name = vlc.strings.resolve_xml_special_chars( name )
            end
            if string.match( line, "<meta name=\"description\"" ) then
               -- Don't ask me why they double encode ...
                _,_,description = string.find( line, "content=\"(.-)\"" )
                description = vlc.strings.resolve_xml_special_chars( description )
                description = vlc.strings.resolve_xml_special_chars( description )
            end
            if string.match( line, "<meta property=\"og:image\"" ) then
                _,_,arturl = string.find( line, "content=\"(.-)\"" )
            end
            -- This is not available in the video parameters (whereas it
            -- is given by the get_video_info API as the "author" field)
            if not artist then
                artist = string.match( line, "yt%-uix%-sessionlink yt%-user%-name[^>]*>([^<]*)</" )
                if artist then
                    artist = vlc.strings.resolve_xml_special_chars( artist )
                end
            end
            -- JSON parameters, also formerly known as "swfConfig",
            -- "SWF_ARGS", "swfArgs", "PLAYER_CONFIG", "playerConfig" ...
            if string.match( line, "ytplayer%.config" ) then

                local js_url = string.match( line, "\"js\": \"(.-)\"" )
                if js_url then
                    js_url = string.gsub( js_url, "\\/", "/" )
                    js_url = string.gsub( js_url, "^//", vlc.access.."://" )
                end

                if not fmt then
                    fmt_list = string.match( line, "\"fmt_list\": \"(.-)\"" )
                    if fmt_list then
                        fmt_list = string.gsub( fmt_list, "\\/", "/" )
                        fmt = get_fmt( fmt_list )
                    end
                end

                url_map = string.match( line, "\"url_encoded_fmt_stream_map\": \"(.-)\"" )
                if url_map then
                    -- FIXME: do this properly
                    url_map = string.gsub( url_map, "\\u0026", "&" )
                    path = pick_url( url_map, fmt, js_url )
                end

                if not path then
                    -- If this is a live stream, the URL map will be empty
                    -- and we get the URL from this field instead
                    local hlsvp = string.match( line, "\"hlsvp\": \"(.-)\"" )
                    if hlsvp then
                        hlsvp = string.gsub( hlsvp, "\\/", "/" )
                        path = hlsvp
                    end
                end
            -- There is also another version of the parameters, encoded
            -- differently, as an HTML attribute of an <object> or <embed>
            -- tag; but we don't need it now
            end
        end

        if not path then
            local video_id = get_url_param( vlc.path, "v" )
            if video_id then
                if fmt then
                    format = "&fmt=" .. fmt
                else
                    format = ""
                end
                -- Without "el=detailpage", /get_video_info fails for many
                -- music videos with errors about copyrighted content being
                -- "restricted from playback on certain sites"
                path = "http://www.youtube.com/get_video_info?video_id="..video_id..format.."&el=detailpage"
                vlc.msg.warn( "Couldn't extract video URL, falling back to alternate youtube API" )
            end
        end

        if not path then
            vlc.msg.err( "Couldn't extract youtube video URL, please check for updates to this script" )
            return { }
        end

        if not arturl then
            arturl = get_arturl()
        end

        return { { path = path; name = name; description = description; artist = artist; arturl = arturl } }

    elseif string.match( vlc.path, "/get_video_info%?" ) then -- video info API
        local line = vlc.readline() -- data is on one line only

        local fmt = get_url_param( vlc.path, "fmt" )
        if not fmt then
            local fmt_list = string.match( line, "&fmt_list=([^&]*)" )
            if fmt_list then
                fmt_list = vlc.strings.decode_uri( fmt_list )
                fmt = get_fmt( fmt_list )
            end
        end

        local url_map = string.match( line, "&url_encoded_fmt_stream_map=([^&]*)" )
        if url_map then
            url_map = vlc.strings.decode_uri( url_map )
            path = pick_url( url_map, fmt )
        end

        if not path then
            -- If this is a live stream, the URL map will be empty
            -- and we get the URL from this field instead
            local hlsvp = string.match( line, "&hlsvp=([^&]*)" )
            if hlsvp then
                hlsvp = vlc.strings.decode_uri( hlsvp )
                path = hlsvp
            end
        end

        if not path then
            vlc.msg.err( "Couldn't extract youtube video URL, please check for updates to this script" )
            return { }
        end

        local title = string.match( line, "&title=([^&]*)" )
        if title then
            title = string.gsub( title, "+", " " )
            title = vlc.strings.decode_uri( title )
        end
        local artist = string.match( line, "&author=([^&]*)" )
        if artist then
            artist = string.gsub( artist, "+", " " )
            artist = vlc.strings.decode_uri( artist )
        end
        local arturl = string.match( line, "&thumbnail_url=([^&]*)" )
        if arturl then
            arturl = vlc.strings.decode_uri( arturl )
        end

        return { { path = path, title = title, artist = artist, arturl = arturl } }

    else -- This is the flash player's URL
        video_id = get_url_param( vlc.path, "video_id" )
        if not video_id then
            _,_,video_id = string.find( vlc.path, "/v/([^?]*)" )
        end
        if not video_id then
            vlc.msg.err( "Couldn't extract youtube video URL" )
            return { }
        end
        fmt = get_url_param( vlc.path, "fmt" )
        if fmt then
            format = "&fmt=" .. fmt
        else
            format = ""
        end
        return { { path = "http://www.youtube.com/watch?v="..video_id..format } }
    end
end


text:
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Unit tests for goog.position.
 *
 * @author eae@google.com (Emil A Eklund)
 */

/** @suppress {extraProvide} */
goog.provide('goog.positioningTest');

goog.require('goog.dom');
goog.require('goog.dom.DomHelper');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.positioning');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.Overflow');
goog.require('goog.positioning.OverflowStatus');
goog.require('goog.style');
goog.require('goog.testing.ExpectedFailures');
goog.require('goog.testing.jsunit');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');

goog.setTestOnly('goog.positioningTest');

// Allow positions to be off by one in gecko as it reports scrolling
// offsets in steps of 2.  Otherwise, allow for subpixel difference
// as seen in IE10+
var ALLOWED_OFFSET = goog.userAgent.GECKO ? 1 : 0.1;
// Error bar for positions since some browsers are not super accurate
// in reporting them.
var EPSILON = 2;

var expectedFailures = new goog.testing.ExpectedFailures();

var corner = goog.positioning.Corner;
var overflow = goog.positioning.Overflow;
var testArea;

function setUp() {
  window.scrollTo(0, 0);

  var viewportSize = goog.dom.getViewportSize();
  // Some tests need enough size viewport.
  if (viewportSize.width < 600 || viewportSize.height < 600) {
    window.moveTo(0, 0);
    window.resizeTo(640, 640);
  }

  testArea = goog.dom.getElement('test-area');
}

function tearDown() {
  expectedFailures.handleTearDown();
  testArea.setAttribute('style', '');
  testArea.innerHTML = '';
}

/**
 * This is used to round pixel values on FF3 Mac.
 */
function assertRoundedEquals(a, b, c) {
  function round(x) {
    return goog.userAgent.GECKO && (goog.userAgent.MAC || goog.userAgent.X11) &&
        goog.userAgent.isVersionOrHigher('1.9') ? Math.round(x) : x;
  }
  if (arguments.length == 3) {
    assertRoughlyEquals(a, round(b), round(c), ALLOWED_OFFSET);
  } else {
    assertRoughlyEquals(round(a), round(b), ALLOWED_OFFSET);
  }
}

function testPositionAtAnchorLeftToRight() {
  var anchor = document.getElementById('anchor1');
  var popup = document.getElementById('popup1');

  // Anchor top left to top left.
  goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                    popup, corner.TOP_LEFT);
  var anchorRect = goog.style.getBounds(anchor);
  var popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Left edge of popup should line up with left edge ' +
                      'of anchor.',
                      anchorRect.left,
                      popupRect.left);
  assertRoundedEquals('Popup should have the same y position as the anchor.',
                      anchorRect.top,
                      popupRect.top);

  // Anchor top left to bottom left.
  goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_LEFT,
                                    popup, corner.TOP_LEFT);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Left edge of popup should line up with left edge ' +
                      'of anchor.',
                      anchorRect.left,
                      popupRect.left);
  assertRoundedEquals('Popup should be positioned just below the anchor.',
                      anchorRect.top + anchorRect.height,
                      popupRect.top);

  // Anchor top left to top right.
  goog.positioning.positionAtAnchor(anchor, corner.TOP_RIGHT,
                                    popup, corner.TOP_LEFT);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Popup should be positioned just right of the anchor.',
                      anchorRect.left + anchorRect.width,
                      popupRect.left);
  assertRoundedEquals('Popup should have the same y position as the anchor.',
                      anchorRect.top,
                      popupRect.top);

  // Anchor top right to bottom right.
  goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
                                    popup, corner.TOP_RIGHT);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Right edge of popup should line up with right edge ' +
                      'of anchor.',
                      anchorRect.left + anchorRect.width,
                      popupRect.left + popupRect.width);
  assertRoundedEquals('Popup should be positioned just below the anchor.',
                      anchorRect.top + anchorRect.height,
                      popupRect.top);

  // Anchor top start to bottom start.
  goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_START,
                                    popup, corner.TOP_START);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Left edge of popup should line up with left edge ' +
                      'of anchor.',
                      anchorRect.left,
                      popupRect.left);
  assertRoundedEquals('Popup should be positioned just below the anchor.',
                      anchorRect.top + anchorRect.height,
                      popupRect.top);
}

function testPositionAtAnchorWithOffset() {
  var anchor = document.getElementById('anchor1');
  var popup = document.getElementById('popup1');

  // Anchor top left to top left with an offset moving the popup away from the
  // anchor.
  goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                    popup, corner.TOP_LEFT,
                                    newCoord(-15, -20));
  var anchorRect = goog.style.getBounds(anchor);
  var popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Left edge of popup should be fifteen pixels from ' +
                      'anchor.',
                      anchorRect.left,
                      popupRect.left + 15);
  assertRoundedEquals('Top edge of popup should be twenty pixels from anchor.',
                      anchorRect.top,
                      popupRect.top + 20);

  // Anchor top left to top left with an offset moving the popup towards the
  // anchor.
  goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                    popup, corner.TOP_LEFT,
                                    newCoord(3, 1));
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Left edge of popup should be three pixels right of ' +
                      'the anchor\'s left edge',
                      anchorRect.left,
                      popupRect.left - 3);
  assertRoundedEquals('Top edge of popup should be one pixel below of the ' +
                      'anchor\'s top edge',
                      anchorRect.top,
                      popupRect.top - 1);
}

function testPositionAtAnchorOverflowLeftEdgeRightToLeft() {
  var anchor = document.getElementById('anchor5');
  var popup = document.getElementById('popup5');

  var status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                                 popup, corner.TOP_RIGHT,
                                                 undefined, undefined,
                                                 overflow.FAIL_X);
  assertFalse('Positioning operation should have failed.',
              (status & goog.positioning.OverflowStatus.FAILED) == 0);

  // Change overflow strategy to ADJUST.
  status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                             popup, corner.TOP_RIGHT,
                                             undefined, undefined,
                                             overflow.ADJUST_X);

  // Fails in Chrome because of infrastructure issues, temporarily disabled.
  // See b/4274723.
  expectedFailures.expectFailureFor(goog.userAgent.product.CHROME);
  try {
    assertTrue('Positioning operation should have been successful.',
               (status & goog.positioning.OverflowStatus.FAILED) == 0);
    assertTrue('Positioning operation should have been adjusted.',
               (status & goog.positioning.OverflowStatus.ADJUSTED_X) != 0);
  } catch (e) {
    expectedFailures.handleException(e);
  }

  var anchorRect = goog.style.getBounds(anchor);
  var popupRect = goog.style.getBounds(popup);
  var parentRect = goog.style.getBounds(anchor.parentNode);
  assertTrue('Position should have been adjusted so that the left edge of ' +
             'the popup is left of the anchor but still within the bounding ' +
             'box of the parent container.',
      anchorRect.left <= popupRect.left <= parentRect.left);

}

function testPositionAtAnchorWithMargin() {
  var anchor = document.getElementById('anchor1');
  var popup = document.getElementById('popup1');

  // Anchor top left to top left.
  goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                    popup, corner.TOP_LEFT, undefined,
                                    new goog.math.Box(1, 2, 3, 4));
  var anchorRect = goog.style.getBounds(anchor);
  var popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Left edge of popup should be four pixels from anchor.',
                      anchorRect.left,
                      popupRect.left - 4);
  assertRoundedEquals('Top edge of popup should be one pixels from anchor.',
                      anchorRect.top,
                      popupRect.top - 1);

  // Anchor top right to bottom right.
  goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
                                    popup, corner.TOP_RIGHT, undefined,
                                    new goog.math.Box(1, 2, 3, 4));
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);

  var visibleAnchorRect = goog.positioning.getVisiblePart_(anchor);

  assertRoundedEquals('Right edge of popup should line up with right edge ' +
                      'of anchor.',
                      visibleAnchorRect.left + visibleAnchorRect.width,
                      popupRect.left + popupRect.width + 2);

  assertRoundedEquals('Popup should be positioned just below the anchor.',
                      visibleAnchorRect.top + visibleAnchorRect.height,
                      popupRect.top - 1);

}

function testPositionAtAnchorRightToLeft() {
  if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('6')) {
    // These tests fails with IE6.
    // TODO(user): Investigate the reason.
    return;
  }

  var anchor = document.getElementById('anchor2');
  var popup = document.getElementById('popup2');

  // Anchor top left to top left.
  goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                    popup, corner.TOP_LEFT);
  var anchorRect = goog.style.getBounds(anchor);
  var popupRect = goog.style.getBounds(popup);

  assertRoundedEquals('Left edge of popup should line up with left edge ' +
                      'of anchor.',
                      anchorRect.left,
                      popupRect.left);
  assertRoundedEquals('Popup should have the same y position as the anchor.',
                      anchorRect.top,
                      popupRect.top);

  // Anchor top start to bottom start.
  goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_START,
                                    popup, corner.TOP_START);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Right edge of popup should line up with right edge ' +
                      'of anchor.',
                      anchorRect.left + anchorRect.width,
                      popupRect.left + popupRect.width);
  assertRoundedEquals('Popup should be positioned just below the anchor.',
                      anchorRect.top + anchorRect.height,
                      popupRect.top);
}

function testPositionAtAnchorRightToLeftWithScroll() {
  if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('6')) {
    // These tests fails with IE6.
    // TODO(user): Investigate the reason.
    return;
  }

  var anchor = document.getElementById('anchor8');
  var popup = document.getElementById('popup8');

  // Anchor top left to top left.
  goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                    popup, corner.TOP_LEFT);
  var anchorRect = goog.style.getBounds(anchor);
  var popupRect = goog.style.getBounds(popup);

  assertRoundedEquals('Left edge of popup should line up with left edge ' +
                      'of anchor.',
                      anchorRect.left,
                      popupRect.left);
  assertRoundedEquals('Popup should have the same y position as the anchor.',
                      anchorRect.top,
                      popupRect.top);

  // Anchor top start to bottom start.
  goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_START,
                                    popup, corner.TOP_START);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);

  var visibleAnchorRect = goog.positioning.getVisiblePart_(anchor);
  var visibleAnchorBox = visibleAnchorRect.toBox();

  assertRoundedEquals('Right edge of popup should line up with right edge ' +
                      'of anchor.',
                      anchorRect.left + anchorRect.width,
                      popupRect.left + popupRect.width);
  assertRoundedEquals('Popup should be positioned just below the anchor.',
                      visibleAnchorBox.bottom,
                      popupRect.top);
}

function testPositionAtAnchorBodyViewport() {
  var anchor = document.getElementById('anchor1');
  var popup = document.getElementById('popup3');

  // Anchor top left to top left.
  goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                    popup, corner.TOP_LEFT);
  var anchorRect = goog.style.getBounds(anchor);
  var popupRect = goog.style.getBounds(popup);
  assertEquals('Left edge of popup should line up with left edge of anchor.',
               anchorRect.left,
               popupRect.left);
  assertRoughlyEquals('Popup should have the same y position as the anchor.',
                      anchorRect.top,
                      popupRect.top,
                      1);

  // Anchor top start to bottom right.
  goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
                                    popup, corner.TOP_RIGHT);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertEquals('Right edge of popup should line up with right edge of anchor.',
               anchorRect.left + anchorRect.width,
               popupRect.left + popupRect.width);
  assertRoughlyEquals('Popup should be positioned just below the anchor.',
                      anchorRect.top + anchorRect.height,
                      popupRect.top,
                      1);

  // Anchor top right to top left.
  goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                    popup, corner.TOP_RIGHT);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertEquals('Right edge of popup should line up with left edge of anchor.',
               anchorRect.left,
               popupRect.left + popupRect.width);
  assertRoughlyEquals('Popup should have the same y position as the anchor.',
                      anchorRect.top,
                      popupRect.top,
                      1);
}

function testPositionAtAnchorSpecificViewport() {
  var anchor = document.getElementById('anchor1');
  var popup = document.getElementById('popup3');

  // Anchor top right to top left within outerbox.
  var status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                                 popup, corner.TOP_RIGHT,
                                                 undefined, undefined,
                                                 overflow.FAIL_X);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertTrue('Positioning operation should have been successful.',
             (status & goog.positioning.OverflowStatus.FAILED) == 0);
  assertTrue('X position should not have been adjusted.',
             (status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0);
  assertTrue('Y position should not have been adjusted.',
             (status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0);
  assertEquals('Right edge of popup should line up with left edge of anchor.',
               anchorRect.left,
               popupRect.left + popupRect.width);
  assertRoughlyEquals('Popup should have the same y position as the anchor.',
                      anchorRect.top,
                      popupRect.top,
                      1);

  // position again within box1.
  var box = document.getElementById('box1');
  var viewport = goog.style.getBounds(box);
  status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                             popup, corner.TOP_RIGHT,
                                             undefined, undefined,
                                             overflow.FAIL_X, undefined,
                                             viewport);
  assertFalse('Positioning operation should have failed.',
              (status & goog.positioning.OverflowStatus.FAILED) == 0);

  // Change overflow strategy to adjust.
  status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                             popup, corner.TOP_RIGHT,
                                             undefined, undefined,
                                             overflow.ADJUST_X, undefined,
                                             viewport);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertTrue('Positioning operation should have been successful.',
             (status & goog.positioning.OverflowStatus.FAILED) == 0);
  assertFalse('X position should have been adjusted.',
              (status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0);
  assertTrue('Y position should not have been adjusted.',
             (status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0);
  assertRoughlyEquals(
      'Left edge of popup should line up with left edge of viewport.',
      viewport.left, popupRect.left, EPSILON);
  assertRoughlyEquals('Popup should have the same y position as the anchor.',
                      anchorRect.top,
                      popupRect.top,
                      1);
}

function testPositionAtAnchorOutsideViewport() {
  var anchor = document.getElementById('anchor4');
  var popup = document.getElementById('popup1');

  var status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
                                                 popup, corner.TOP_RIGHT);
  var anchorRect = goog.style.getBounds(anchor);
  var popupRect = goog.style.getBounds(popup);
  assertTrue('Positioning operation should have been successful.',
             (status & goog.positioning.OverflowStatus.FAILED) == 0);
  assertTrue('X position should not have been adjusted.',
             (status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0);
  assertTrue('Y position should not have been adjusted.',
             (status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0);

  assertEquals('Right edge of popup should line up with left edge of anchor.',
               anchorRect.left,
               popupRect.left + popupRect.width);

  // Change overflow strategy to fail.
  status = goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
                                             popup, corner.TOP_RIGHT,
                                             undefined, undefined,
                                             overflow.FAIL_X);
  assertFalse('Positioning operation should have failed.',
              (status & goog.positioning.OverflowStatus.FAILED) == 0);

  // Change overflow strategy to adjust.
  status = goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
                                             popup, corner.TOP_RIGHT,
                                             undefined, undefined,
                                             overflow.ADJUST_X);
  anchorRect = goog.style.getBounds(anchor);
  popupRect = goog.style.getBounds(popup);
  assertTrue('Positioning operation should have been successful.',
             (status & goog.positioning.OverflowStatus.FAILED) == 0);
  assertFalse('X position should have been adjusted.',
              (status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0);
  assertTrue('Y position should not have been adjusted.',
             (status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0);
  assertRoughlyEquals(
      'Left edge of popup should line up with left edge of viewport.',
      0, popupRect.left, EPSILON);
  assertEquals('Popup should be positioned just below the anchor.',
               anchorRect.top + anchorRect.height,
               popupRect.top);
}

function testAdjustForViewportFailIgnore() {
  var f = goog.positioning.adjustForViewport_;
  var viewport = new goog.math.Box(100, 200, 200, 100);
  var overflow = goog.positioning.Overflow.IGNORE;

  var pos = newCoord(150, 150);
  var size = newSize(50, 50);
  assertEquals('Viewport overflow should be ignored.',
               goog.positioning.OverflowStatus.NONE,
               f(pos, size, viewport, overflow));

  pos = newCoord(150, 150);
  size = newSize(100, 50);
  assertEquals('Viewport overflow should be ignored.',
               goog.positioning.OverflowStatus.NONE,
               f(pos, size, viewport, overflow));

  pos = newCoord(50, 50);
  size = newSize(50, 50);
  assertEquals('Viewport overflow should be ignored.',
               goog.positioning.OverflowStatus.NONE,
               f(pos, size, viewport, overflow));
}

function testAdjustForViewportFailXY() {
  var f = goog.positioning.adjustForViewport_;
  var viewport = new goog.math.Box(100, 200, 200, 100);
  var overflow = goog.positioning.Overflow.FAIL_X |
                 goog.positioning.Overflow.FAIL_Y;

  var pos = newCoord(150, 150);
  var size = newSize(50, 50);
  assertEquals('Element should not overflow viewport.',
               goog.positioning.OverflowStatus.NONE,
               f(pos, size, viewport, overflow));

  pos = newCoord(150, 150);
  size = newSize(100, 50);
  assertEquals('Element should overflow the right edge of viewport.',
               goog.positioning.OverflowStatus.FAILED_RIGHT,
               f(pos, size, viewport, overflow));

  pos = newCoord(150, 150);
  size = newSize(50, 100);
  assertEquals('Element should overflow the bottom edge of viewport.',
               goog.positioning.OverflowStatus.FAILED_BOTTOM,
               f(pos, size, viewport, overflow));

  pos = newCoord(50, 150);
  size = newSize(50, 50);
  assertEquals('Element should overflow the left edge of viewport.',
               goog.positioning.OverflowStatus.FAILED_LEFT,
               f(pos, size, viewport, overflow));

  pos = newCoord(150, 50);
  size = newSize(50, 50);
  assertEquals('Element should overflow the top edge of viewport.',
               goog.positioning.OverflowStatus.FAILED_TOP,
               f(pos, size, viewport, overflow));

  pos = newCoord(50, 50);
  size = newSize(50, 50);
  assertEquals('Element should overflow the left & top edges of viewport.',
               goog.positioning.OverflowStatus.FAILED_LEFT |
               goog.positioning.OverflowStatus.FAILED_TOP,
               f(pos, size, viewport, overflow));
}

function testAdjustForViewportAdjustXFailY() {
  var f = goog.positioning.adjustForViewport_;
  var viewport = new goog.math.Box(100, 200, 200, 100);
  var overflow = goog.positioning.Overflow.ADJUST_X |
                 goog.positioning.Overflow.FAIL_Y;

  var pos = newCoord(150, 150);
  var size = newSize(50, 50);
  assertEquals('Element should not overflow viewport.',
               goog.positioning.OverflowStatus.NONE,
               f(pos, size, viewport, overflow));
  assertEquals('X Position should not have been changed.', 150, pos.x);
  assertEquals('Y Position should not have been changed.', 150, pos.y);

  pos = newCoord(150, 150);
  size = newSize(100, 50);
  assertEquals('Element position should be adjusted not to overflow right ' +
               'edge of viewport.',
               goog.positioning.OverflowStatus.ADJUSTED_X,
               f(pos, size, viewport, overflow));
  assertEquals('X Position should be adjusted to 100.', 100, pos.x);
  assertEquals('Y Position should not have been changed.', 150, pos.y);

  pos = newCoord(50, 150);
  size = newSize(100, 50);
  assertEquals('Element position should be adjusted not to overflow left ' +
               'edge of viewport.',
               goog.positioning.OverflowStatus.ADJUSTED_X,
               f(pos, size, viewport, overflow));
  assertEquals('X Position should be adjusted to 100.', 100, pos.x);
  assertEquals('Y Position should not have been changed.', 150, pos.y);

  pos = newCoord(50, 50);
  size = newSize(100, 50);
  assertEquals('Element position should be adjusted not to overflow left ' +
               'edge of viewport, should overflow bottom edge.',
               goog.positioning.OverflowStatus.ADJUSTED_X |
               goog.positioning.OverflowStatus.FAILED_TOP,
               f(pos, size, viewport, overflow));
  assertEquals('X Position should be adjusted to 100.', 100, pos.x);
  assertEquals('Y Position should not have been changed.', 50, pos.y);
}

function testAdjustForViewportResizeHeight() {
  var f = goog.positioning.adjustForViewport_;
  var viewport = new goog.math.Box(0, 200, 200, 0);
  var overflow = goog.positioning.Overflow.RESIZE_HEIGHT;

  var pos = newCoord(150, 150);
  var size = newSize(25, 100);
  assertEquals('Viewport height should be resized.',
               goog.positioning.OverflowStatus.HEIGHT_ADJUSTED,
               f(pos, size, viewport, overflow));
  assertEquals('Height should be resized to 50.',
               50, size.height);
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  var pos = newCoord(0, 0);
  var size = newSize(50, 250);
  assertEquals('Viewport height should be resized.',
               goog.positioning.OverflowStatus.HEIGHT_ADJUSTED,
               f(pos, size, viewport, overflow));
  assertEquals('Height should be resized to 200.',
               200, size.height);
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  var pos = newCoord(0, -50);
  var size = newSize(50, 240);
  assertEquals('Viewport height should be resized.',
               goog.positioning.OverflowStatus.HEIGHT_ADJUSTED,
               f(pos, size, viewport, overflow));
  assertEquals('Height should be resized to 190.',
               190, size.height);
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  var pos = newCoord(0, -50);
  var size = newSize(50, 300);
  assertEquals('Viewport height should be resized.',
               goog.positioning.OverflowStatus.HEIGHT_ADJUSTED,
               f(pos, size, viewport, overflow));
  assertEquals('Height should be resized to 200.',
               200, size.height);
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  pos = newCoord(150, 150);
  size = newSize(50, 50);
  assertEquals('No Viewport overflow.',
               goog.positioning.OverflowStatus.NONE,
               f(pos, size, viewport, overflow));
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  var offsetViewport = new goog.math.Box(100, 200, 300, 0);
  var pos = newCoord(0, 50);
  var size = newSize(50, 240);
  assertEquals('Viewport height should be resized.',
               goog.positioning.OverflowStatus.HEIGHT_ADJUSTED,
               f(pos, size, offsetViewport, overflow));
  assertEquals('Height should be resized to 190.',
               190, size.height);
  assertTrue('Output box is within viewport',
             offsetViewport.contains(new goog.math.Box(pos.y,
                                                       pos.x + size.width,
                                                       pos.y + size.height,
                                                       pos.x)));
}

function testAdjustForViewportResizeWidth() {
  var f = goog.positioning.adjustForViewport_;
  var viewport = new goog.math.Box(0, 200, 200, 0);
  var overflow = goog.positioning.Overflow.RESIZE_WIDTH;

  var pos = newCoord(150, 150);
  var size = newSize(100, 25);
  assertEquals('Viewport width should be resized.',
               goog.positioning.OverflowStatus.WIDTH_ADJUSTED,
               f(pos, size, viewport, overflow));
  assertEquals('Width should be resized to 50.',
               50, size.width);
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  var pos = newCoord(0, 0);
  var size = newSize(250, 50);
  assertEquals('Viewport width should be resized.',
               goog.positioning.OverflowStatus.WIDTH_ADJUSTED,
               f(pos, size, viewport, overflow));
  assertEquals('Width should be resized to 200.',
               200, size.width);
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  var pos = newCoord(-50, 0);
  var size = newSize(240, 50);
  assertEquals('Viewport width should be resized.',
               goog.positioning.OverflowStatus.WIDTH_ADJUSTED,
               f(pos, size, viewport, overflow));
  assertEquals('Width should be resized to 190.',
               190, size.width);
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  var pos = newCoord(-50, 0);
  var size = newSize(300, 50);
  assertEquals('Viewport width should be resized.',
               goog.positioning.OverflowStatus.WIDTH_ADJUSTED,
               f(pos, size, viewport, overflow));
  assertEquals('Width should be resized to 200.',
               200, size.width);
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  pos = newCoord(150, 150);
  size = newSize(50, 50);
  assertEquals('No Viewport overflow.',
               goog.positioning.OverflowStatus.NONE,
               f(pos, size, viewport, overflow));
  assertTrue('Output box is within viewport',
             viewport.contains(new goog.math.Box(pos.y, pos.x + size.width,
                                                 pos.y + size.height, pos.x)));

  var offsetViewport = new goog.math.Box(0, 300, 200, 100);
  var pos = newCoord(50, 0);
  var size = newSize(240, 50);
  assertEquals('Viewport width should be resized.',
               goog.positioning.OverflowStatus.WIDTH_ADJUSTED,
               f(pos, size, offsetViewport, overflow));
  assertEquals('Width should be resized to 190.',
               190, size.width);
  assertTrue('Output box is within viewport',
             offsetViewport.contains(new goog.math.Box(pos.y,
                                                       pos.x + size.width,
                                                       pos.y + size.height,
                                                       pos.x)));
}

function testPositionAtAnchorWithResizeHeight() {
  var anchor = document.getElementById('anchor9');
  var popup = document.getElementById('popup9');
  var box = document.getElementById('box9');
  var viewport = goog.style.getBounds(box);

  var status = goog.positioning.positionAtAnchor(
      anchor, corner.TOP_START, popup, corner.TOP_START,
      new goog.math.Coordinate(0, -20), null,
      goog.positioning.Overflow.RESIZE_HEIGHT, null,
      viewport.toBox());
  assertEquals('Status should be HEIGHT_ADJUSTED.',
               goog.positioning.OverflowStatus.HEIGHT_ADJUSTED, status);

  var TOLERANCE = 0.1;
  // Adjust the viewport to allow some tolerance for subpixel positioning,
  // this is required for this test to pass on IE10,11
  viewport.top -= TOLERANCE;
  viewport.left -= TOLERANCE;

  assertTrue('Popup ' + goog.style.getBounds(popup) +
             ' not is within viewport' + viewport,
             viewport.contains(goog.style.getBounds(popup)));
}

function testPositionAtCoordinateResizeHeight() {
  var f = goog.positioning.positionAtCoordinate;
  var viewport = new goog.math.Box(0, 50, 50, 0);
  var overflow = goog.positioning.Overflow.RESIZE_HEIGHT |
      goog.positioning.Overflow.ADJUST_Y;
  var popup = document.getElementById('popup1');
  var corner = goog.positioning.Corner.BOTTOM_LEFT;

  var pos = newCoord(100, 100);

  assertEquals('Viewport height should be resized.',
               goog.positioning.OverflowStatus.HEIGHT_ADJUSTED |
               goog.positioning.OverflowStatus.ADJUSTED_Y,
               f(pos, popup, corner, undefined, viewport, overflow));
  var bounds = goog.style.getSize(popup);
  assertEquals('Height should be resized to the size of the viewport.',
               50, bounds.height);
}

function testGetPositionAtCoordinateResizeHeight() {
  var f = goog.positioning.getPositionAtCoordinate;
  var viewport = new goog.math.Box(0, 50, 50, 0);
  var overflow = goog.positioning.Overflow.RESIZE_HEIGHT |
      goog.positioning.Overflow.ADJUST_Y;
  var popup = document.getElementById('popup1');
  var corner = goog.positioning.Corner.BOTTOM_LEFT;

  var pos = newCoord(100, 100);
  var size = goog.style.getSize(popup);

  var result = f(pos, size, corner, undefined, viewport, overflow);
  assertEquals('Viewport height should be resized.',
               goog.positioning.OverflowStatus.HEIGHT_ADJUSTED |
               goog.positioning.OverflowStatus.ADJUSTED_Y,
               result.status);
  assertEquals('Height should be resized to the size of the viewport.',
               50, result.rect.height);
}

function testGetEffectiveCornerLeftToRight() {
  var f = goog.positioning.getEffectiveCorner;
  var el = document.getElementById('ltr');

  assertEquals('TOP_LEFT should be unchanged for ltr.',
               corner.TOP_LEFT,
               f(el, corner.TOP_LEFT));
  assertEquals('TOP_RIGHT should be unchanged for ltr.',
               corner.TOP_RIGHT,
               f(el, corner.TOP_RIGHT));
  assertEquals('BOTTOM_LEFT should be unchanged for ltr.',
               corner.BOTTOM_LEFT,
               f(el, corner.BOTTOM_LEFT));
  assertEquals('BOTTOM_RIGHT should be unchanged for ltr.',
               corner.BOTTOM_RIGHT,
               f(el, corner.BOTTOM_RIGHT));

  assertEquals('TOP_START should be TOP_LEFT for ltr.',
               corner.TOP_LEFT,
               f(el, corner.TOP_START));
  assertEquals('TOP_END should be TOP_RIGHT for ltr.',
               corner.TOP_RIGHT,
               f(el, corner.TOP_END));
  assertEquals('BOTTOM_START should be BOTTOM_LEFT for ltr.',
               corner.BOTTOM_LEFT,
               f(el, corner.BOTTOM_START));
  assertEquals('BOTTOM_END should be BOTTOM_RIGHT for ltr.',
               corner.BOTTOM_RIGHT,
               f(el, corner.BOTTOM_END));
}

function testGetEffectiveCornerRightToLeft() {
  var f = goog.positioning.getEffectiveCorner;
  var el = document.getElementById('rtl');

  assertEquals('TOP_LEFT should be unchanged for rtl.',
               corner.TOP_LEFT,
               f(el, corner.TOP_LEFT));
  assertEquals('TOP_RIGHT should be unchanged for rtl.',
               corner.TOP_RIGHT,
               f(el, corner.TOP_RIGHT));
  assertEquals('BOTTOM_LEFT should be unchanged for rtl.',
               corner.BOTTOM_LEFT,
               f(el, corner.BOTTOM_LEFT));
  assertEquals('BOTTOM_RIGHT should be unchanged for rtl.',
               corner.BOTTOM_RIGHT,
               f(el, corner.BOTTOM_RIGHT));

  assertEquals('TOP_START should be TOP_RIGHT for rtl.',
               corner.TOP_RIGHT,
               f(el, corner.TOP_START));
  assertEquals('TOP_END should be TOP_LEFT for rtl.',
               corner.TOP_LEFT,
               f(el, corner.TOP_END));
  assertEquals('BOTTOM_START should be BOTTOM_RIGHT for rtl.',
               corner.BOTTOM_RIGHT,
               f(el, corner.BOTTOM_START));
  assertEquals('BOTTOM_END should be BOTTOM_LEFT for rtl.',
               corner.BOTTOM_LEFT,
               f(el, corner.BOTTOM_END));
}

function testFlipCornerHorizontal() {
  var f = goog.positioning.flipCornerHorizontal;

  assertEquals('TOP_LEFT should be flipped to TOP_RIGHT.',
               corner.TOP_RIGHT,
               f(corner.TOP_LEFT));
  assertEquals('TOP_RIGHT should be flipped to TOP_LEFT.',
               corner.TOP_LEFT,
               f(corner.TOP_RIGHT));
  assertEquals('BOTTOM_LEFT should be flipped to BOTTOM_RIGHT.',
               corner.BOTTOM_RIGHT,
               f(corner.BOTTOM_LEFT));
  assertEquals('BOTTOM_RIGHT should be flipped to BOTTOM_LEFT.',
               corner.BOTTOM_LEFT,
               f(corner.BOTTOM_RIGHT));

  assertEquals('TOP_START should be flipped to TOP_END.',
               corner.TOP_END,
               f(corner.TOP_START));
  assertEquals('TOP_END should be flipped to TOP_START.',
               corner.TOP_START,
               f(corner.TOP_END));
  assertEquals('BOTTOM_START should be flipped to BOTTOM_END.',
               corner.BOTTOM_END,
               f(corner.BOTTOM_START));
  assertEquals('BOTTOM_END should be flipped to BOTTOM_START.',
               corner.BOTTOM_START,
               f(corner.BOTTOM_END));
}

function testFlipCornerVertical() {
  var f = goog.positioning.flipCornerVertical;

  assertEquals('TOP_LEFT should be flipped to BOTTOM_LEFT.',
               corner.BOTTOM_LEFT,
               f(corner.TOP_LEFT));
  assertEquals('TOP_RIGHT should be flipped to BOTTOM_RIGHT.',
               corner.BOTTOM_RIGHT,
               f(corner.TOP_RIGHT));
  assertEquals('BOTTOM_LEFT should be flipped to TOP_LEFT.',
               corner.TOP_LEFT,
               f(corner.BOTTOM_LEFT));
  assertEquals('BOTTOM_RIGHT should be flipped to TOP_RIGHT.',
               corner.TOP_RIGHT,
               f(corner.BOTTOM_RIGHT));

  assertEquals('TOP_START should be flipped to BOTTOM_START.',
               corner.BOTTOM_START,
               f(corner.TOP_START));
  assertEquals('TOP_END should be flipped to BOTTOM_END.',
               corner.BOTTOM_END,
               f(corner.TOP_END));
  assertEquals('BOTTOM_START should be flipped to TOP_START.',
               corner.TOP_START,
               f(corner.BOTTOM_START));
  assertEquals('BOTTOM_END should be flipped to TOP_END.',
               corner.TOP_END,
               f(corner.BOTTOM_END));
}

function testFlipCorner() {
  var f = goog.positioning.flipCorner;

  assertEquals('TOP_LEFT should be flipped to BOTTOM_RIGHT.',
               corner.BOTTOM_RIGHT,
               f(corner.TOP_LEFT));
  assertEquals('TOP_RIGHT should be flipped to BOTTOM_LEFT.',
               corner.BOTTOM_LEFT,
               f(corner.TOP_RIGHT));
  assertEquals('BOTTOM_LEFT should be flipped to TOP_RIGHT.',
               corner.TOP_RIGHT,
               f(corner.BOTTOM_LEFT));
  assertEquals('BOTTOM_RIGHT should be flipped to TOP_LEFT.',
               corner.TOP_LEFT,
               f(corner.BOTTOM_RIGHT));

  assertEquals('TOP_START should be flipped to BOTTOM_END.',
               corner.BOTTOM_END,
               f(corner.TOP_START));
  assertEquals('TOP_END should be flipped to BOTTOM_START.',
               corner.BOTTOM_START,
               f(corner.TOP_END));
  assertEquals('BOTTOM_START should be flipped to TOP_END.',
               corner.TOP_END,
               f(corner.BOTTOM_START));
  assertEquals('BOTTOM_END should be flipped to TOP_START.',
               corner.TOP_START,
               f(corner.BOTTOM_END));
}

function testPositionAtAnchorFrameViewportStandard() {
  var iframe = document.getElementById('iframe-standard');
  var iframeDoc = goog.dom.getFrameContentDocument(iframe);
  assertTrue(new goog.dom.DomHelper(iframeDoc).isCss1CompatMode());

  new goog.dom.DomHelper(iframeDoc).getDocumentScrollElement().scrollTop = 100;
  var anchor = iframeDoc.getElementById('anchor1');
  var popup = document.getElementById('popup6');

  var status = goog.positioning.positionAtAnchor(
      anchor, corner.TOP_RIGHT, popup, corner.BOTTOM_RIGHT);
  var iframeRect = goog.style.getBounds(iframe);
  var popupRect = goog.style.getBounds(popup);
  assertEquals('Status should not have any ADJUSTED and FAILED.',
               goog.positioning.OverflowStatus.NONE, status);
  assertRoundedEquals('Popup should be positioned just above the iframe, ' +
                      'not above the anchor element inside the iframe',
                      iframeRect.top,
                      popupRect.top + popupRect.height);
}

function testPositionAtAnchorFrameViewportQuirk() {
  var iframe = document.getElementById('iframe-quirk');
  var iframeDoc = goog.dom.getFrameContentDocument(iframe);
  assertFalse(new goog.dom.DomHelper(iframeDoc).isCss1CompatMode());

  window.scrollTo(0, 100);
  new goog.dom.DomHelper(iframeDoc).getDocumentScrollElement().scrollTop = 100;
  var anchor = iframeDoc.getElementById('anchor1');
  var popup = document.getElementById('popup6');

  var status = goog.positioning.positionAtAnchor(
      anchor, corner.TOP_RIGHT, popup, corner.BOTTOM_RIGHT);
  var iframeRect = goog.style.getBounds(iframe);
  var popupRect = goog.style.getBounds(popup);
  assertEquals('Status should not have any ADJUSTED and FAILED.',
               goog.positioning.OverflowStatus.NONE, status);
  assertRoundedEquals('Popup should be positioned just above the iframe, ' +
                      'not above the anchor element inside the iframe',
                      iframeRect.top,
                      popupRect.top + popupRect.height);
}

function testPositionAtAnchorFrameViewportWithPopupInScroller() {
  var iframe = document.getElementById('iframe-standard');
  var iframeDoc = goog.dom.getFrameContentDocument(iframe);

  new goog.dom.DomHelper(iframeDoc).getDocumentScrollElement().scrollTop = 100;
  var anchor = iframeDoc.getElementById('anchor1');
  var popup = document.getElementById('popup7');
  popup.offsetParent.scrollTop = 50;

  var status = goog.positioning.positionAtAnchor(
      anchor, corner.TOP_RIGHT, popup, corner.BOTTOM_RIGHT);
  var iframeRect = goog.style.getBounds(iframe);
  var popupRect = goog.style.getBounds(popup);
  assertEquals('Status should not have any ADJUSTED and FAILED.',
               goog.positioning.OverflowStatus.NONE, status);
  assertRoughlyEquals('Popup should be positioned just above the iframe, ' +
      'not above the anchor element inside the iframe',
      iframeRect.top,
      popupRect.top + popupRect.height,
      ALLOWED_OFFSET);
}

function testPositionAtAnchorNestedFrames() {
  var outerIframe = document.getElementById('nested-outer');
  var outerDoc = goog.dom.getFrameContentDocument(outerIframe);
  var popup = outerDoc.getElementById('popup1');
  var innerIframe = outerDoc.getElementById('inner-frame');
  var innerDoc = goog.dom.getFrameContentDocument(innerIframe);
  var anchor = innerDoc.getElementById('anchor1');

  var status = goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.BOTTOM_LEFT);
  assertEquals('Status should not have any ADJUSTED and FAILED.',
               goog.positioning.OverflowStatus.NONE, status);
  var innerIframeRect = goog.style.getBounds(innerIframe);
  var popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Top of frame should align with bottom of the popup',
                      innerIframeRect.top, popupRect.top + popupRect.height);

  // The anchor is scrolled up by 10px.
  // Popup position should be the same as above.
  goog.dom.getWindow(innerDoc).scrollTo(0, 10);
  status = goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.BOTTOM_LEFT);
  assertEquals('Status should not have any ADJUSTED and FAILED.',
               goog.positioning.OverflowStatus.NONE, status);
  innerIframeRect = goog.style.getBounds(innerIframe);
  popupRect = goog.style.getBounds(popup);
  assertRoundedEquals('Top of frame should align with bottom of the popup',
                      innerIframeRect.top, popupRect.top + popupRect.height);
}

function testPositionAtAnchorOffscreen() {
  var offset = 0;
  var anchor = goog.dom.getElement('offscreen-anchor');
  var popup = goog.dom.getElement('popup3');

  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectEquals(
      newCoord(offset, offset), goog.style.getPageOffset(popup));

  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null,
      overflow.ADJUST_X_EXCEPT_OFFSCREEN | overflow.ADJUST_Y);
  assertObjectEquals(
      newCoord(-1000, offset), goog.style.getPageOffset(popup));

  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y_EXCEPT_OFFSCREEN);
  assertObjectEquals(
      newCoord(offset, -1000), goog.style.getPageOffset(popup));

  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null,
      overflow.ADJUST_X_EXCEPT_OFFSCREEN | overflow.ADJUST_Y_EXCEPT_OFFSCREEN);
  assertObjectEquals(
      newCoord(-1000, -1000),
      goog.style.getPageOffset(popup));
}

function testPositionAtAnchorWithOverflowScrollOffsetParent() {
  var testAreaOffset = goog.style.getPageOffset(testArea);
  var scrollbarWidth = goog.style.getScrollbarWidth();
  window.scrollTo(testAreaOffset.x, testAreaOffset.y);

  var overflowDiv = goog.dom.createElement('div');
  overflowDiv.style.overflow = 'scroll';
  overflowDiv.style.position = 'relative';
  goog.style.setSize(overflowDiv, 200 /* width */, 100 /* height */);

  var anchor = goog.dom.createElement('div');
  anchor.style.position = 'absolute';
  goog.style.setSize(anchor, 50 /* width */, 50 /* height */);
  goog.style.setPosition(anchor, 300 /* left */, 300 /* top */);

  var popup = createPopupDiv(75 /* width */, 50 /* height */);

  goog.dom.append(testArea, overflowDiv, anchor);
  goog.dom.append(overflowDiv, popup);

  // Popup should always be positioned within the overflowDiv
  goog.style.setPosition(overflowDiv, 0 /* left */, 0 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 200 - 75 - scrollbarWidth,
          testAreaOffset.y + 100 - 50 - scrollbarWidth),
      goog.style.getPageOffset(popup),
      1);

  goog.style.setPosition(overflowDiv, 400 /* left */, 0 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_RIGHT, popup, corner.TOP_LEFT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 400, testAreaOffset.y + 100 - 50 - scrollbarWidth),
      goog.style.getPageOffset(popup),
      1);

  goog.style.setPosition(overflowDiv, 0 /* left */, 400 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.BOTTOM_LEFT, popup, corner.BOTTOM_RIGHT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 200 - 75 - scrollbarWidth, testAreaOffset.y + 400),
      goog.style.getPageOffset(popup),
      1);

  goog.style.setPosition(overflowDiv, 400 /* left */, 400 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.BOTTOM_RIGHT, popup, corner.BOTTOM_LEFT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 400, testAreaOffset.y + 400),
      goog.style.getPageOffset(popup),
      1);

  // No overflow.
  goog.style.setPosition(overflowDiv, 300 - 50 /* left */, 300 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 300 - 50, testAreaOffset.y + 300),
      goog.style.getPageOffset(popup),
      1);
}

function testPositionAtAnchorWithOverflowHiddenParent() {
  var testAreaOffset = goog.style.getPageOffset(testArea);
  window.scrollTo(testAreaOffset.x, testAreaOffset.y);

  var overflowDiv = goog.dom.createElement('div');
  overflowDiv.style.overflow = 'hidden';
  overflowDiv.style.position = 'relative';
  goog.style.setSize(overflowDiv, 200 /* width */, 100 /* height */);

  var anchor = goog.dom.createElement('div');
  anchor.style.position = 'absolute';
  goog.style.setSize(anchor, 50 /* width */, 50 /* height */);
  goog.style.setPosition(anchor, 300 /* left */, 300 /* top */);

  var popup = createPopupDiv(75 /* width */, 50 /* height */);

  goog.dom.append(testArea, overflowDiv, anchor);
  goog.dom.append(overflowDiv, popup);

  // Popup should always be positioned within the overflowDiv
  goog.style.setPosition(overflowDiv, 0 /* left */, 0 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 200 - 75, testAreaOffset.y + 100 - 50),
      goog.style.getPageOffset(popup),
      1);

  goog.style.setPosition(overflowDiv, 400 /* left */, 0 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_RIGHT, popup, corner.TOP_LEFT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 400, testAreaOffset.y + 100 - 50),
      goog.style.getPageOffset(popup),
      1);

  goog.style.setPosition(overflowDiv, 0 /* left */, 400 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.BOTTOM_LEFT, popup, corner.BOTTOM_RIGHT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 200 - 75, testAreaOffset.y + 400),
      goog.style.getPageOffset(popup),
      1);

  goog.style.setPosition(overflowDiv, 400 /* left */, 400 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.BOTTOM_RIGHT, popup, corner.BOTTOM_LEFT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 400, testAreaOffset.y + 400),
      goog.style.getPageOffset(popup),
      1);

  // No overflow.
  goog.style.setPosition(overflowDiv, 300 - 50 /* left */, 300 /* top */);
  goog.positioning.positionAtAnchor(
      anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null,
      overflow.ADJUST_X | overflow.ADJUST_Y);
  assertObjectRoughlyEquals(
      new goog.math.Coordinate(
          testAreaOffset.x + 300 - 50, testAreaOffset.y + 300),
      goog.style.getPageOffset(popup),
      1);
}

function createPopupDiv(width, height) {
  var popupDiv = goog.dom.createElement('div');
  popupDiv.style.position = 'absolute';
  goog.style.setSize(popupDiv, width, height);
  goog.style.setPosition(popupDiv, 0 /* left */, 250 /* top */);
  return popupDiv;
}

function newCoord(x, y) {
  return new goog.math.Coordinate(x, y);
}

function newSize(w, h) {
  return new goog.math.Size(w, h);
}

function newBox(coord, size) {
}