/** Command test. */ @Test public final void replace() { // query to count number of documents final String count = "count(db:open('" + NAME + "'))"; // database must be opened to replace resources no(new Replace(FILE, "xxx")); ok(new CreateDB(NAME, FILE)); assertEquals("1", ok(new XQuery(count))); // replace existing document ok(new Replace(FN, "<a/>")); assertEquals("1", ok(new XQuery(count))); // replace existing document (again) ok(new Replace(FN, "<a/>")); assertEquals("1", ok(new XQuery(count))); // invalid content no(new Replace(FN, "")); assertEquals("1", ok(new XQuery(count))); // create and replace binary file ok(new XQuery("db:store('" + NAME + "', 'a', 'a')")); ok(new Replace("a", "<b/>")); assertTrue(ok(new XQuery("db:open('" + NAME + "')")).length() != 0); ok(new XQuery("db:retrieve('" + NAME + "', 'a')")); // a failing replace should not remove existing documents no(new Replace(FN, "<a>")); assertEquals("1", ok(new XQuery(count))); }
/** * Test sending of HTTP GET requests. * * @throws Exception exception */ @Test public void postGet() throws Exception { // GET1 - just send a GET request try (final QueryProcessor qp = new QueryProcessor( _HTTP_SEND_REQUEST.args("<http:request method='get' href='" + REST_ROOT + "'/>"), ctx)) { final Value v = qp.value(); checkResponse(v, 2, HttpURLConnection.HTTP_OK); assertEquals(NodeType.DOC, v.itemAt(1).type); } // GET2 - with override-media-type='text/plain' try (final QueryProcessor qp = new QueryProcessor( _HTTP_SEND_REQUEST.args( "<http:request method='get' override-media-type='text/plain'/>", REST_ROOT), ctx)) { final Value v = qp.value(); checkResponse(v, 2, HttpURLConnection.HTTP_OK); assertEquals(AtomType.STR, v.itemAt(1).type); } // Get3 - with status-only='true' try (final QueryProcessor qp = new QueryProcessor( _HTTP_SEND_REQUEST.args("<http:request method='get' status-only='true'/>", REST_ROOT), ctx)) { checkResponse(qp.value(), 1, HttpURLConnection.HTTP_OK); } }
/** * Tests method setRequestContent of HttpClient. * * @throws IOException I/O Exception */ @Test public void writeMultipartMessage() throws IOException { final HttpRequest req = new HttpRequest(); req.isMultipart = true; req.payloadAttrs.put("media-type", "multipart/alternative"); req.payloadAttrs.put("boundary", "boundary42"); final Part p1 = new Part(); p1.headers.put("Content-Type", "text/plain; charset=us-ascii"); p1.bodyAttrs.put("media-type", "text/plain"); final String plain = "...plain text...."; p1.bodyContent.add(Str.get(plain + '\n')); final Part p2 = new Part(); p2.headers.put("Content-Type", "text/richtext"); p2.bodyAttrs.put("media-type", "text/richtext"); final String rich = ".... richtext version..."; p2.bodyContent.add(Str.get(rich)); final Part p3 = new Part(); p3.headers.put("Content-Type", "text/x-whatever"); p3.bodyAttrs.put("media-type", "text/x-whatever"); final String fancy = ".... fanciest formatted version..."; p3.bodyContent.add(Str.get(fancy)); req.parts.add(p1); req.parts.add(p2); req.parts.add(p3); final FakeHttpConnection fakeConn = new FakeHttpConnection(new URL("http://www.test.com")); HttpClient.setRequestContent(fakeConn.getOutputStream(), req); final String expResult = "--boundary42" + CRLF + "Content-Type: text/plain; charset=us-ascii" + CRLF + CRLF + plain + Prop.NL + CRLF + "--boundary42" + CRLF + "Content-Type: text/richtext" + CRLF + CRLF + rich + CRLF + "--boundary42" + CRLF + "Content-Type: text/x-whatever" + CRLF + CRLF + fancy + CRLF + "--boundary42--" + CRLF; // Compare results assertEquals(expResult, fakeConn.getOutputStream().toString()); }
/** * Checks if namespace hierarchy structure is updated correctly on the descendant axis after a * NSNode has been inserted. */ @Test public void insertIntoShiftPreValues() { create(12); query("insert node <b xmlns:ns='A'/> into doc('d12')/*:a/*:b"); assertEquals( NL + " Pre[3] xmlns:ns=\"A\"" + NL + " Pre[4] xmlns=\"B\"", context.data().nspaces.toString()); }
/** Detects malformed namespace hierarchy. */ @Test public void nsHierarchy() { create(9); query("insert node <f xmlns='F'/> into doc('d9')//*:e"); assertEquals( NL + " Pre[1] xmlns=\"A\"" + NL + " Pre[4] xmlns=\"D\"" + NL + " Pre[6] xmlns=\"F\"", context.data().nspaces.toString()); }
/** * Checks if namespace hierarchy structure is updated correctly on the descendant axis after a * NSNode has been deleted. */ @Test public void deleteShiftPreValues3() { create(15); query("delete node doc('d15')/*:a/*:c"); assertEquals( NL + " Pre[1] xmlns=\"A\"" + NL + " Pre[2] xmlns=\"B\"" + NL + " Pre[3] xmlns=\"E\"", context.data().nspaces.toString()); }
/** * Checks the response to an HTTP request. * * @param v query result * @param itemsCount expected number of items * @param expStatus expected status */ private static void checkResponse(final Value v, final int itemsCount, final int expStatus) { assertEquals(itemsCount, v.size()); assertTrue(v.itemAt(0) instanceof FElem); final FElem response = (FElem) v.itemAt(0); assertNotNull(response.attributes()); if (!eq(response.attribute(STATUS), token(expStatus))) { fail("Expected: " + expStatus + "\nFound: " + response); } }
/** * Runs a query and checks the serialization parameters. * * @throws IOException I/O exception */ @Test public void queryOptions() throws IOException { final Query query = session.query("declare option output:encoding 'US-ASCII';()"); query.execute(); final SerializerOptions sp = new SerializerOptions(); sp.parse(query.options()); assertEquals("US-ASCII", sp.get(SerializerOptions.ENCODING)); query.close(); }
/** * Tests an erroneous query. * * @throws Exception exception */ @Test public void error() throws Exception { try (final QueryProcessor qp = new QueryProcessor( _HTTP_SEND_REQUEST.args("<http:request method='get'/>", RESTURL + "unknown") + "[1]/@status/data()", ctx)) { assertEquals("404", qp.value().serialize().toString()); } }
/** * Tests writing of body content when @method is raw and output is xs:hexBinary. * * @throws IOException I/O Exception */ @Test public void writeHex() throws IOException { // Case 1: content is xs:hexBinary final HttpRequest req1 = new HttpRequest(); req1.payloadAttrs.put("method", SerialMethod.BASEX.toString()); req1.bodyContent.add(new Hex(token("test"))); final FakeHttpConnection fakeConn1 = new FakeHttpConnection(new URL("http://www.test.com")); HttpClient.setRequestContent(fakeConn1.getOutputStream(), req1); assertEquals(fakeConn1.out.toString(Strings.UTF8), "test"); // Case 2: content is a node final HttpRequest req2 = new HttpRequest(); req2.payloadAttrs.put("method", SerialMethod.BASEX.toString()); final FElem e3 = new FElem("a").add("test"); req2.bodyContent.add(e3); final FakeHttpConnection fakeConn2 = new FakeHttpConnection(new URL("http://www.test.com")); HttpClient.setRequestContent(fakeConn2.getOutputStream(), req2); assertEquals(fakeConn2.out.toString(), "<a>test</a>"); }
/** Detects malformed namespace hierarchy inserting an element. */ @Test public void nsHierarchy3() { query( transform("<a xmlns='x'/>", "insert node <a xmlns='y'/> into $input"), "<a xmlns='x'><a xmlns='y'/></a>"); // in-depth test create(2); query("insert node <a xmlns='y'/> into doc('d2')//*:x"); assertEquals( NL + " Pre[1] xmlns=\"xx\"" + NL + " Pre[2] xmlns=\"y\"", context.data().nspaces.toString()); }
/** * Tests writing of request content with different combinations of the body attributes media-type * and method. * * @throws IOException IO exception */ @Test public void writeMessage() throws IOException { // Case 1: No method, media-type='text/xml' final HttpRequest req1 = new HttpRequest(); final FakeHttpConnection fakeConn1 = new FakeHttpConnection(new URL("http://www.test.com")); req1.payloadAttrs.put(SerializerOptions.MEDIA_TYPE.name(), "text/xml"); // Node child final FElem e1 = new FElem("a").add("a"); req1.bodyContent.add(e1); // String item child req1.bodyContent.add(Str.get("<b>b</b>")); HttpClient.setRequestContent(fakeConn1.getOutputStream(), req1); assertEquals("<a>a</a><b>b</b>", fakeConn1.out.toString(Strings.UTF8)); // Case 2: No method, media-type='text/plain' final HttpRequest req2 = new HttpRequest(); final FakeHttpConnection fakeConn2 = new FakeHttpConnection(new URL("http://www.test.com")); req2.payloadAttrs.put(SerializerOptions.MEDIA_TYPE.name(), "text/plain"); // Node child final FElem e2 = new FElem("a").add("a"); req2.bodyContent.add(e2); // String item child req2.bodyContent.add(Str.get("<b>b</b>")); HttpClient.setRequestContent(fakeConn2.getOutputStream(), req2); assertEquals("a<b>b</b>", fakeConn2.out.toString()); // Case 3: method='text', media-type='text/xml' final HttpRequest req3 = new HttpRequest(); final FakeHttpConnection fakeConn3 = new FakeHttpConnection(new URL("http://www.test.com")); req3.payloadAttrs.put(SerializerOptions.MEDIA_TYPE.name(), "text/xml"); req3.payloadAttrs.put("method", "text"); // Node child final FElem e3 = new FElem("a").add("a"); req3.bodyContent.add(e3); // String item child req3.bodyContent.add(Str.get("<b>b</b>")); HttpClient.setRequestContent(fakeConn3.getOutputStream(), req3); assertEquals("a<b>b</b>", fakeConn3.out.toString()); }
/** Test method. */ @Test public void updateEntries() { String list = query(_ZIP_ENTRIES.args(ZIP)); // create and compare identical zip file query(_ZIP_UPDATE_ENTRIES.args(list, TMPZIP)); final String list2 = query(_ZIP_ENTRIES.args(TMPZIP)); assertEquals(list.replaceAll(" href=\".*?\"", ""), list2.replaceAll(" href=\".*?\"", "")); // remove one directory list = list.replaceAll("<zip:dir name=.test.>.*</zip:dir>", ""); query(_ZIP_UPDATE_ENTRIES.args(list, TMPZIP)); }
/** * Tests response handling with specified charset in the header 'Content-Type'. * * @throws IOException I/O Exception * @throws QueryException query exception */ @Test public void responseWithCharset() throws IOException, QueryException { // Create fake HTTP connection final FakeHttpConnection conn = new FakeHttpConnection(new URL("http://www.test.com")); // Set content type conn.contentType = "text/plain; charset=CP1251"; // set content encoded in CP1251 final String test = "\u0442\u0435\u0441\u0442"; conn.content = Charset.forName("CP1251").encode(test).array(); final ItemList res = new HttpResponse(null, ctx.options).getResponse(conn, true, null); // compare results assertEquals(test, string(res.get(1).string(null))); }
/** * Checks the response to an HTTP request. * * @param c command * @param expStatus expected status * @param itemsCount expected number of items * @throws QueryException query exception */ private void checkResponse(final Command c, final int expStatus, final int itemsCount) throws QueryException { assertTrue(c.result() instanceof ItemIter); final ItemIter res = (ItemIter) c.result(); assertEquals(itemsCount, res.size()); assertTrue(res.item[0] instanceof FElem); final FElem response = (FElem) res.item[0]; assertNotNull(response.attr()); final NodeIter resAttr = response.attr(); Nod attr = null; while ((attr = resAttr.next()) != null) { if (Token.eq(attr.nname(), STATUS)) assertTrue(eq(attr.atom(), token(expStatus))); } }
/** * Tests RequestParser.parse() with normal (not multipart) request. * * @throws IOException I/O Exception * @throws QueryException query exception */ @Test public void parseRequest() throws IOException, QueryException { // Simple HTTP request with no errors final String req = "<http:request " + "xmlns:http='http://expath.org/ns/http-client' " + "method='POST' href='" + REST_ROOT + "'>" + "<http:header name='hdr1' value='hdr1val'/>" + "<http:header name='hdr2' value='hdr2val'/>" + "<http:body media-type='text/xml'>" + "Test body content" + "</http:body>" + "</http:request>"; final DBNode dbNode = new DBNode(new IOContent(req)); final HttpRequestParser rp = new HttpRequestParser(null); final HttpRequest r = rp.parse(dbNode.children().next(), null); assertEquals(2, r.attributes.size()); assertEquals(2, r.headers.size()); assertTrue(r.bodyContent.size() != 0); assertEquals(1, r.payloadAttrs.size()); }
/** * Compares results. * * @param expected expected result * @param returned returned result * @throws Exception exception */ private static void compare(final ItemList expected, final ItemList returned) throws Exception { // Compare response with expected result assertEquals("Different number of results", expected.size(), returned.size()); final long es = expected.size(); for (int e = 0; e < es; e++) { final Item exp = expected.get(e), ret = returned.get(e); if (!new DeepEqual().equal(exp, ret)) { final TokenBuilder tb = new TokenBuilder("Result ").addLong(e).add(" differs:\nReturned: "); tb.addExt(ret.serialize()).add("\nExpected: ").addExt(exp.serialize()); fail(tb.toString()); } } }
/** * Checks if namespace hierarchy structure is updated correctly on the descendant axis after a * NSNode has been inserted. */ @Test public void insertIntoShiftPreValues3() { create(14); query("insert node <n xmlns='D'/> into doc('d14')/*:a/*:b"); assertEquals( NL + " Pre[1] xmlns=\"A\"" + NL + " Pre[2] xmlns=\"B\"" + NL + " Pre[3] xmlns=\"D\"" + NL + " Pre[4] xmlns=\"C\"", context.data().nspaces.toString()); }
/** Inserts an attribute with namespace. */ @Test public void insertAttributeWithNs() { create(1); query("insert node attribute { QName('ns', 'pref:local') } { } into /*"); final Data data = context.data(); assertEquals(false, data.nsFlag(0)); assertEquals(true, data.nsFlag(1)); assertEquals(false, data.nsFlag(2)); assertEquals(0, data.uriId(1, data.kind(1))); assertEquals(1, data.uriId(2, data.kind(2))); assertEquals("ns", string(data.nspaces.uri(1))); }
/** Test query. Detects malformed namespace hierarchy. */ @Test @Ignore public void xuty0004() { final String query = "declare variable $input-context external;" + "let $source as node()* := (" + " <status>on leave</status>," + " <!-- for 6 months -->" + " )," + " $target := $input-context/works[1]/employee[1]" + "return insert nodes $source into $target"; try (final QueryProcessor qp = new QueryProcessor(query, context)) { qp.value(); } catch (final QueryException ex) { assertEquals("XUTY0004", ex.error().code); } fail("should throw XUTY0004"); }
/** * Tests writing of request content when @src is set. * * @throws IOException I/O Exception */ @Test public void writeFromResource() throws IOException { // Create a file form which will be read final IOFile file = new IOFile(Prop.TMP, Util.className(FnHttpTest.class)); file.write(token("test")); // Request final HttpRequest req = new HttpRequest(); req.payloadAttrs.put("src", file.url()); req.payloadAttrs.put("method", "binary"); // HTTP connection final FakeHttpConnection fakeConn = new FakeHttpConnection(new URL("http://www.test.com")); HttpClient.setRequestContent(fakeConn.getOutputStream(), req); // Delete file file.delete(); assertEquals(fakeConn.out.toString(Strings.UTF8), "test"); }
/** * Writes back updates. * * @throws IOException I/O exception */ @Test public void writeBack() throws IOException { INPUT.write(token("<a>X</a>")); run("-i", INPUT.toString(), "-u", "-q", "delete node //text()"); assertEquals("<a/>", string(INPUT.read())); }
/** * Assert a cache entry is found in the cache. * * @param key key * @param size number of index hits * @param pointer pointer to id list */ private void assertCacheEntry(final byte[] key, final int size, final long pointer) { final IndexEntry entry = cache.get(key); assertEquals(entry.size, size); assertEquals(entry.offset, pointer); }
/** * Checks if namespace hierarchy structure is updated correctly on the descendant axis after a * NSNode has been deleted. */ @Test public void deleteShiftPreValues() { create(12); query("delete node doc('d12')/a/b"); assertEquals(NL + " Pre[2] xmlns=\"B\"", context.data().nspaces.toString()); }
/** Tests if a namespace node is deleted. */ @Test public void delete2() { create(21); query("delete node //b"); assertEquals(NL + " Pre[2] xmlns:p1=\"u1\"", context.data().nspaces.toString()); }
/** * Tests parsing of multipart request when the contents for each part are set from the $bodies * parameter. * * @throws IOException I/O Exception * @throws QueryException query exception */ @Test public void parseMultipartReqBodies() throws IOException, QueryException { final String multiReq = "<http:request " + "xmlns:http='http://expath.org/ns/http-client' " + "method='POST' href='" + REST_ROOT + "'>" + "<http:header name='hdr1' value='hdr1val'/>" + "<http:header name='hdr2' value='hdr2val'/>" + "<http:multipart media-type='multipart/mixed' boundary='xxxx'>" + "<http:header name='p1hdr1' value='p1hdr1val'/>" + "<http:header name='p1hdr2' value='p1hdr2val'/>" + "<http:body media-type='text/plain'/>" + "<http:header name='p2hdr1' value='p2hdr1val'/>" + "<http:body media-type='text/plain'/>" + "<http:body media-type='text/plain'/>" + "</http:multipart>" + "</http:request>"; final DBNode dbNode1 = new DBNode(new IOContent(multiReq)); final ItemList bodies = new ItemList(); bodies.add(Str.get("Part1")); bodies.add(Str.get("Part2")); bodies.add(Str.get("Part3")); final HttpRequestParser rp = new HttpRequestParser(null); final HttpRequest r = rp.parse(dbNode1.children().next(), bodies.iter()); assertEquals(2, r.attributes.size()); assertEquals(2, r.headers.size()); assertTrue(r.isMultipart); assertEquals(3, r.parts.size()); // check parts final Iterator<Part> i = r.parts.iterator(); Part part = i.next(); assertEquals(2, part.headers.size()); assertEquals(1, part.bodyContent.size()); assertEquals(1, part.bodyAttrs.size()); part = i.next(); assertEquals(1, part.headers.size()); assertEquals(1, part.bodyContent.size()); assertEquals(1, part.bodyAttrs.size()); part = i.next(); assertEquals(0, part.headers.size()); assertEquals(1, part.bodyContent.size()); assertEquals(1, part.bodyAttrs.size()); }
/** Checks duplicate namespace declarations. */ @Test public void avoidDuplicateNSDeclaration() { create(19); query("let $b := <a xmlns:x='X' x:id='0'/> " + "return insert node $b//@*:id into /*:n"); assertEquals(1, context.data().namespaces(1).size()); }
/** * Checks if namespace hierarchy structure is updated correctly on the descendant axis after a * NSNode has been inserted. */ @Test public void insertIntoShiftPreValues2() { create(13); query("insert node <c/> as first into doc('d13')/a"); assertEquals(NL + " Pre[3] xmlns=\"A\"", context.data().nspaces.toString()); }
/** * Assumes that the nodes have the specified number of nodes. * * @param nodes context nodes * @param size expected size */ private static void ok(final Nodes nodes, final int size) { if (nodes != null) assertEquals(size, nodes.size()); }
/** * Checks if the most recent output equals the specified string. * * @param exp expected string * @param ret string returned from the client API */ private void assertEqual(final Object exp, final Object ret) { final String result = (out != null ? out : ret).toString(); if (out != null) out.reset(); assertEquals(exp.toString(), result.replaceAll("\\r|\\n", "")); }