TestDemo

来源:互联网 发布:王兆山 真相 知乎 编辑:程序博客网 时间:2024/05/01 00:36

SimpleLocate

package com.infy.tests;import org.openqa.selenium.*;import org.openqa.selenium.firefox.FirefoxDriver;//import org.openqa.selenium.By;//import java.util.*;import java.io.*;import java.util.List;public class SimpleLocate {public static void main(String[] args) throws InterruptedException,Exception {// TODO Auto-generated method stubWebDriver dr = new FirefoxDriver();File file = new File("src/form.html");String filePath = "file:///" + file.getAbsolutePath();System.out.printf("now accesss %s \n", filePath);dr.get(filePath);Thread.sleep(2000);// by iddr.findElement(By.id("inputEmail")).click();dr.findElement(By.id("inputEmail")).sendKeys("lm_soso@sina.com");Thread.sleep(1000);// by namedr.findElement(By.name("password"));System.out.println("this is password text box");Thread.sleep(1000);// by tagnameString classOfForm = dr.findElement(By.tagName("form")).getAttribute("class");System.out.println(classOfForm);System.out.printf("%s\n", classOfForm);Thread.sleep(1000);// by link text/* * WebElement link = dr.findElement(By.linkText("register")); * ((JavascriptExecutor * )dr).executeScript("$(arguments[0]).fadeOut().fadeIn()", link); * Thread.sleep(1000); *  * // by partial link test WebElement sameLink = * dr.findElement(By.partialLinkText("reg")); * ((JavascriptExecutor)dr).executeScript * ("$(arguments[0]).fadeOut().fadeIn()", sameLink); Thread.sleep(1000); *  * // by css selector WebElement div = * dr.findElement(By.cssSelector(".controls")); * ((JavascriptExecutor)dr). * executeScript("$(arguments[0]).fadeOut().fadeIn()", div); * Thread.sleep(1000); *  * // by xpath * dr.findElement(By.xpath("/html/body/form/div[3]/div/label/input" * )).click(); Thread.sleep(1000); *  * System.out.println("browser will be close"); */dr.quit();// by id --Email Text Box// dr.findElement(By.id("inputEmail")).click();/* * WebElement EmailTextBox = dr.findElement(By.id("inputEmail")); * EmailTextBox.sendKeys("lm_soso@sina.com"); * System.out.println("Email Text box"); Thread.sleep(1000); *  * // by name ---Password Text Box WebElement PswTextBox = * dr.findElement(By.name("password")); PswTextBox.sendKeys("Password"); * Thread.sleep(1000); *//* * // by tagname String classOfForm = * dr.findElement(By.tagName("form")).getAttribute( "class"); //String * classofForm = dr.findElement(By.tagName("form")) * System.out.printf("%s\n", classOfForm); * System.out.println("by tagname"); Thread.sleep(1000); *  * // by link text--register link WebElement link = * dr.findElement(By.linkText("register")); ((JavascriptExecutor) * dr).executeScript( "$(arguments[0]).fadeOut().fadeIn()", link); * WebElement link = dr.findElement(By.linkText("register")); * link.click(); System.out.println("Click the register link"); * Thread.sleep(1000); */// by partial link test ---// WebElement sameLink = dr.findElement(By.partialLinkText("reg"));// ((JavascriptExecutor) dr).executeScript(// "$(arguments[0]).fadeOut().fadeIn()", sameLink);// WebElement rembCheckBox =// dr.findElement(By.cssSelector("input[type=\"checkbox\"]"));// if (rembCheckBox.isSelected()){// System.out.println("already select remember me");// } else {// rembCheckBox.click();// System.out.println("select this check box");// }// Thread.sleep(1000);/* * // by css selector WebElement div = * dr.findElement(By.cssSelector(".controls")); ((JavascriptExecutor) * dr).executeScript( "$(arguments[0]).fadeOut().fadeIn()", div); * Thread.sleep(1000); *  * // by xpath * dr.findElement(By.xpath("/html/body/form/div[3]/div/label/input")) * .click(); Thread.sleep(1000); *  * System.out.println("browser will be close"); *//* * WebElement checkbox1 = dr.findElement(By.id("c1")); * checkbox1.click(); checkbox1.click(); * System.out.println(checkbox1.getAttribute("input id")); // * dr.navigate().refresh(); System.out.println("select checkbox1"); *//* * // 选择所有的checkbox并全部勾上 List<WebElement> checkboxes = * dr.findElements(By .cssSelector("input[type=checkbox]")); for * (WebElement checkbox : checkboxes) { checkbox.click(); } * dr.navigate().refresh(); *  * // 打印当前页面上有多少个checkbox System.out.printf("%d\n", checkboxes.size()); *  * // 选择页面上所有的input,然后从中过滤出所有的checkbox并勾选之 List<WebElement> inputs = * dr.findElements(By.tagName("input")); for (WebElement input : inputs) * { if (input.getAttribute("type").equals("checkbox")) { input.click(); * } } *  * // 把页面上最后1个checkbox的勾给去掉 List<WebElement> allCheckboxes = * dr.findElements(By .cssSelector("input[type=checkbox]")); * allCheckboxes.get(allCheckboxes.size() - 1).click(); *  * Thread.sleep(1000); System.out.println("browser will be close"); *//* dr.quit(); */}}

TestBreadCrumb

<html>        <head>            <meta http-equiv="content-type" content="text/html;charset=utf-8" />            <title>breadcrumb</title>                   <script type="text/javascript" async="" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>            <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />                  <script type="text/javascript">                $(document).ready(                    function(){                    }                );            </script>        </head>        <body>            <h3>breadcrumb</h3>            <div class="row-fluid">                <div class="span3">                         <ul class="breadcrumb">                        <li><a href="#">Home</a> <span class="divider">/</span></li>                        <li><a href="#">Library</a> <span class="divider">/</span></li>                        <li class="active">Data</li>                    </ul>                </div>                  </div>              </body>        <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>    </html>


import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.*;import java.io.*;import java.util.*;public class TestBreadCrumb {public static void main(String[] args) throws InterruptedException {// TODO Auto-generated method stubWebDriver dr = new FirefoxDriver();File file = new File("src/breadcrumb.html");String filePath = "file:///" + file.getAbsolutePath();System.out.printf("now accesss %s \n", filePath);dr.get(filePath);Thread.sleep(1000);// 获得其父层级/* * List<WebElement> ancestors = * dr.findElement(By.className("breadcrumb")) * .findElements(By.tagName("a")); for (WebElement link : ancestors) { * System.out.println(link.getText()); } */List<WebElement> bread = dr.findElement(By.className("breadcrumb")).findElements(By.tagName("a"));for (WebElement link : bread) {System.out.println(link.getText());}// 获取当前层级// 由于页面上可能有很多class为active的元素// 所以使用层级定位最为保险WebElement current = dr.findElement(By.className("breadcrumb")).findElement(By.className("active"));System.out.println(current.getText());Thread.sleep(1000);System.out.println("browser will be close");dr.quit();}}
</pre><p>TestButtonDropdown</p><pre name="code" class="html"><html>        <head>            <meta http-equiv="content-type" content="text/html;charset=utf-8" />            <title>button group</title>                 <script type="text/javascript" async="" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>            <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />                  <script type="text/javascript">                $(document).ready(function(){                    $('.btn').click(function(){                        alert($(this).text());                    });                });                     </script>        </head>        <body>            <h3>button group</h3>            <div class="row-fluid">                <div class="span3">                         <div class="well">                        <div class="btn-toolbar">                            <div class="btn-group">                                <div class="btn">first</div>                                <div class="btn">second</div>                                <div class="btn">third</div>                            </div>                        </div>                    </div>                          </div>                  </div>              </body>        <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>    </html>


import org.openqa.selenium.*;import org.openqa.selenium.firefox.*;import org.openqa.selenium.support.ui.ExpectedCondition;import org.openqa.selenium.support.ui.WebDriverWait;import java.io.*;public class TestButtonDropdown {public static void main(String[] args) throws InterruptedException {// TODO Auto-generated method stubWebDriver dr = new FirefoxDriver();File file = new File("src/button_dropdown.html");String filePath = "file:///" + file.getAbsolutePath();System.out.printf("now accesss %s \n", filePath);dr.get(filePath);Thread.sleep(1000);// 定位text是watir-webdriver的下拉菜单// 首先显示下拉菜单dr.findElement(By.linkText("Info")).click();(new WebDriverWait(dr, 10)).until(new ExpectedCondition<Boolean>() {public Boolean apply(WebDriver d) {return d.findElement(By.className("dropdown-menu")).isDisplayed();}});// 通过ul再层级定位dr.findElement(By.className("dropdown-menu")).findElement(By.linkText("watir-webdriver")).click();Thread.sleep(1000);System.out.println("browser will be close");dr.quit();}}
TestButtonGroup

<html>        <head>            <meta http-equiv="content-type" content="text/html;charset=utf-8" />            <title>button group</title>                 <script type="text/javascript" async="" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>            <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />                  <script type="text/javascript">                $(document).ready(function(){                    $('.btn').click(function(){                        alert($(this).text());                    });                });                     </script>        </head>        <body>            <h3>button group</h3>            <div class="row-fluid">                <div class="span3">                         <div class="well">                        <div class="btn-toolbar">                            <div class="btn-group">                                <div class="btn">first</div>                                <div class="btn">second</div>                                <div class="btn">third</div>                            </div>                        </div>                    </div>                          </div>                  </div>              </body>        <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>    </html>


import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.*;import java.io.*;import java.util.*;public class TestButtonGroup {public static void main(String[] args) {// TODO Auto-generated method stubWebDriver dr = new FirefoxDriver();File file = new File("src/button_group.html");String filepath = "file:///" + file.getAbsolutePath();dr.get(filepath);List<WebElement> btns = dr.findElements(By.className("btn"));for (WebElement btn : btns) {if (btn.getText().equals("second")) {btn.click();break;}}// dr.close();dr.quit();}}
TestModal

<html>        <head>            <meta http-equiv="content-type" content="text/html;charset=utf-8" />            <title>modal</title>                    <script type="text/javascript" async="" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>            <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />                  <script type="text/javascript">                $(document).ready(function(){                    $('#click').click(function(){                        $(this).parent().find('p').text('try watir-webdriver right now!');                    });                });            </script>        </head>        <body>            <h3>modal</h3>            <div class="row-fluid">                <div class="span6">                         <!-- Button to trigger modal -->                    <a href="#myModal" role="button" class="btn btn-primary" data-toggle="modal" id="show_modal">Click</a>                    <!-- Modal -->                    <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">                      <div class="modal-header">                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">�</button>                        <h3 id="myModalLabel">Modal header</h3>                      </div>                      <div class="modal-body">                        <p>watir-webdriver is better than slenium-webdriver</p>                        <a href="#" id="click">click me</a>                      </div>                      <div class="modal-footer">                        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>                        <button class="btn btn-primary">Save changes</button>                      </div>                    </div>                </div>                  </div>              </body>        <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>    </html>

package com.infy.tests;import java.io.File;//import java.util.List;import org.openqa.selenium.By;import org.openqa.selenium.JavascriptExecutor;//import org.openqa.selenium.Keys;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.*;import org.openqa.selenium.support.ui.ExpectedCondition;import org.openqa.selenium.support.ui.WebDriverWait;public class TestModal {public static void main(String[] args) throws InterruptedException {// TODO Auto-generated method stubWebDriver dr = new FirefoxDriver();File file = new File("src/modal.html");String filePath = "file:///" + file.getAbsolutePath();System.out.printf("now accesss %s \n", filePath);dr.get(filePath);Thread.sleep(1000);// 打开对话框dr.findElement(By.id("show_modal")).click();(new WebDriverWait(dr, 10)).until(new ExpectedCondition<Boolean>() {public Boolean apply(WebDriver d) {return d.findElement(By.id("myModal")).isDisplayed();}});// 点击对话框中的链接// 由于对话框中的元素被蒙板所遮挡,直接点击会报 Element is not clickable的错误// 所以使用js来模拟click// 在watir-webdriver中只需要fire_event(:click)就可以了<pre name="code" class="java">

TestNavs

<html>        <head>            <meta http-equiv="content-type" content="text/html;charset=utf-8" />            <title>Navs</title>                 <script type="text/javascript" async="" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>            <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />                  <script type="text/javascript">                $(document).ready(                    function(){                        $('.nav').find('li').click(function() {                            $(this).parent().find('li').removeClass('active');                            $(this).addClass('active');                        });                    }                );            </script>        </head>        <body>            <h3>Navs</h3>            <div class="row-fluid">                <div class="span3">                         <ul class="nav nav-pills">                        <li class="active">                            <a href="#">Home</a>                        </li>                        <li><a href="#">Content</a></li>                        <li><a href="#">About</a></li>                    </ul>                </div>                  </div>              </body>        <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>    </html>


import org.openqa.selenium.*;import org.openqa.selenium.firefox.*;import java.io.*;public class TestNavs {public static void main(String[] args) throws InterruptedException {// TODO Auto-generated method stubWebDriver dr = new FirefoxDriver();File file = new File("src/navs.html");String filePath = "file:///" + file.getAbsolutePath();System.out.printf("now accesss %s \n", filePath);dr.get(filePath);Thread.sleep(1000);// 方法1:层级定位,先定位ul再定位lidr.findElement(By.className("nav")).findElement(By.linkText("About")).click();Thread.sleep(1000);// 分层定位content// dr.findElement(By.className("nav")).findElement(By.linkText("Content")).click();dr.findElement(By.xpath("/html/body/div/div/ul/li[2]")).click();// 方法2: 直接定位linkdr.findElement(By.linkText("Home")).click();Thread.sleep(1000);System.out.println("browser will be close");dr.quit();}}

TestReg

package com.infy.tests;import java.util.regex.*;public class TestReg {public enum Mycolor {red, green, blue};public static void main(String[] args) {//Mycolor m = Mycolor.blue;//public enum Mycolor {red, green, blue};// * . + ?//System.out.println("a".matches("a*"));//System.out.println("aaaa".matches("a*"));//System.out.println("".matches("a*"));//System.out.println("a".matches("a*"));//System.out.println("a".matches("a+"));//System.out.println("1234566".matches("\\d*{3,100}"));//System.out.println("".matches("a?"));//System.out.println("a".matches("[abc]"));//System.out.println("a".matches("[^abc]"));//System.out.println("a".matches("[a-zA-Z]"));//System.out.println("ab".matches("[a-zA-Z]"));//System.out.println("a".matches("[a-z]|A-Z]"));//System.out.println("a".matches("[a-z[A-Z]]"));//System.out.println("r".matches("[a-z&&[rfg]]"));//recognize \s \w \d \//System.out.println(" \n\r\t".matches("\\s{4}"));//System.out.println(" ".matches("\\s"));//System.out.println("a_6".matches("\\w{3}"));//System.out.println("abc888&^%".matches("[a-z]{3}\\d+[&^%]+"));//System.out.println("\\".matches("\\\\"));//boundary/*System.out.println("hello sir".matches("^h.*"));System.out.println("hello sir".matches("^h.*r$"));System.out.println("hello sir".matches(".*o\\b.*"));System.out.println(" \n".matches("[\\s&&[^\\n]]*\\n$"));System.out.println("aaa 88888c".matches(".*\\d{5}.*"));*//*Pattern p = Pattern.compile("\\d{3,5}");String s = "123-1234-12345-234-00";Matcher m = p.matcher(s);//System.out.println(m.matches());System.out.println(m.find());System.out.println(m.start() + "-" + m.end());System.out.println(m.find());System.out.println(m.start() + "-" + m.end());System.out.println(m.find());System.out.println(m.start() + "-" + m.end());System.out.println(m.find());//System.out.println(m.find());//System.out.println(m.lookingAt());*///start end//System.out.println(m.find());//replacement/*Pattern p = Pattern.compile("java",Pattern.CASE_INSENSITIVE);Matcher m = p.matcher("JAVA ILOVEJava you java");System.out.println(m.replaceAll("JAVA"));*//*//groupPattern p = Pattern.compile("(\\d{3,5})([a-z]{2})");String s = "123aa-1234dd-12345cc-234dd-00dd";Matcher m = p.matcher(s);while (m.find()) {System.out.println(m.group(1));}*///lm_soso@sina.com  ".*@.*\..*"//System.out.println("lm_soso@sina.com".matches(".*@.*..*"));/*Pattern p = Pattern.compile(".*@.*..*");String s = "adfd<> fdfd lm_soso@sina.com";Matcher m = p.matcher(s);while (m.find()) {System.out.println(m.group()); }*/}}

TestSendKeys

<html>        <head>            <meta http-equiv="content-type" content="text/html;charset=utf-8" />            <title>send keys</title>                    <script type="text/javascript" async="" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>            <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />              </head>        <body>            <h3>send keys</h3>            <div class="row-fluid">            <div class="span3">                     <div class="well">                    <label>A</label>                    <textarea rows="10", cols="10" id="A">I think watir-webdriver is better than selenium-webdriver</textarea>                </div>                      </div>            <div class="span3">                     <div class="well">                    <label>B</label>                    <textarea rows="10", cols="10" id="B"></textarea>                </div>                      </div>            </div>              </body>        <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>    </html>


package com.infy.tests;import org.openqa.selenium.*;import org.openqa.selenium.firefox.*;import java.io.*;public class TestSendKeys {public static void main(String[] args) throws InterruptedException {// TODO Auto-generated method stubWebDriver dr = new FirefoxDriver();// File file = new File("src/send_keys.html");File file = new File("src/form.html");String filePath = "file:///" + file.getAbsolutePath();// System.out.printf("now accesss %s \n", filePath);dr.get(filePath);Thread.sleep(1000);// String s =// dr.findElement(By.cssSelector("input[type=\"checkbox\"]")).getText();// System.out.println(s);// copy content of A// System.out.println(Keys.chord(Keys.CONTROL+"a"));// dr.findElement(By.id("A")).sendKeys(Keys.chord(Keys.CONTROL + "a"));// String s = dr.findElement(By.id("A")).getText();// System.out.println(dr.findElement(By.id("A")).getAttribute("rows"));// System.out.println(s);dr.findElement(By.id("A")).sendKeys(Keys.chord(Keys.CONTROL + "a"));Thread.sleep(1000);dr.findElement(By.id("A")).sendKeys(Keys.chord(Keys.CONTROL + "x"));// paste to Bdr.findElement(By.id("B")).sendKeys(Keys.chord(Keys.CONTROL + "v"));// SendKeys to Adr.findElement(By.id("A")).sendKeys(Keys.chord("watir webdriver is better than selenium webdriver"));/* * dr.findElement(By.id("A")).sendKeys( * "watir webdriver is better than selenium webdriver"); * Thread.sleep(1000); System.out.println("browser will be close"); */dr.quit();}}

TestSort
package com.infy.tests;public class TestSort {public static void main(String[] args) {// TODO Auto-generated method stubint[] src = {2,4,7,4,9,8,3,1};doSelectSort2(src);}public static void doSelectSort(int[] src) {int len = src.length;int temp;for (int i = 0; i < len; i++) {temp = src[i];int j;int smallestLocation = i;for (j = i + 1; j < len; j++) {if (src[j] < temp) {temp = src[j];smallestLocation = j;}}src[smallestLocation]=src[i];src[i]=temp;}for (int l=0;l<src.length;l++){System.out.println(src[l]);}}public static void doSelectSort2(int[] src){//int temp;int len=src.length;for(int i=0; i<len; i++){int temp;int j;temp=src[i];int smallestLocation = i;for (j=i+1; j<len; j++){if(src[j]<temp){temp=src[j];smallestLocation = j;}}src[smallestLocation]=src[i];src[i]=temp;}//System.out.println(src);for (int l=0;l<src.length;l++){System.out.println(src[l]);}}}






0 0
原创粉丝点击