package com.canoo.webtest.extension; import com.canoo.webtest.engine.Context; import com.canoo.webtest.engine.StepFailedException; import com.canoo.webtest.steps.Step; import com.gargoylesoftware.htmlunit.html.HtmlTable; import com.gargoylesoftware.htmlunit.html.HtmlTableCell; import com.gargoylesoftware.htmlunit.html.HtmlTableRow; import java.util.ArrayList; import java.util.List; import junit.framework.Assert; /** * */ public class VerifyTableStep extends Step { private String content = ""; private String excludedColumns; private String htmlid; @Override public void doExecute() throws Exception { Context context = getContext(); HtmlTable table; if (htmlid == null) { throw new StepFailedException("\'htmlid\' attribute of the html table should be set"); } table = (HtmlTable)context.getCurrentHtmlResponse(this).getHtmlElementById(htmlid); assertEquals(toArray(content), toArray(table, excludedColumns)); } public void addText(String msg) { this.content += msg; } public void setExcludedColumns(String excludedColumns) { this.excludedColumns = excludedColumns; } private static List> toArray(String description) { List> rows = new ArrayList>(); for (String line : description.trim().split("\n")) { if (line.trim().length() == 0) { continue; } List row = new ArrayList(); String inside = line.substring(line.indexOf("|") + 1, line.lastIndexOf("|")); for (String cell : inside.split("\\|")) { row.add(cell.trim()); } rows.add(row); } return rows; } private static List> toArray(HtmlTable table, String someExcludedColumns) { List excludedColumnIndexes = getColumnIndexes(someExcludedColumns); List> rows = new ArrayList>(); List htmlRows = table.getHtmlElementsByTagName("tr"); for (HtmlTableRow htmlRow : htmlRows) { List row = new ArrayList(); List cells = htmlRow.getCells(); for (int indexCell = 0; indexCell < cells.size(); indexCell++) { if (!excludedColumnIndexes.contains(indexCell)) { row.add(cells.get(indexCell).asText().trim()); } } rows.add(row); } return rows; } private static List getColumnIndexes(String description) { List result = new ArrayList(); if (description != null) { for (String item : description.split(",")) { result.add(Integer.parseInt(item.trim())); } } return result; } private void assertEquals(List> expected, List> actual) { if (expected.size() != actual.size()) { throw new StepFailedException( "Unmatching number of lines '" + htmlid + "' : expected : " + expected.size() + ", actual : " + actual.size()); } for (int i = 0; i < expected.size(); i++) { Assert.assertEquals("Comparison failure for the table '" + htmlid + "' line " + i + " :", expected.get(i), actual.get(i)); } } public void setHtmlid(String htmlid) { this.htmlid = htmlid; } }