Giter Club home page Giter Club logo

couchbasemock's Introduction

CouchbaseMock - The Couchbase Test Server

CouchbaseMock is a test server implementing some of the memcached protocol which is used by some SDKs (including the C SDK) for basic testing. While it is recommended that testing be done against the real server, CouchbaseMock is useful as being self-contained (there is no need to install it to the system) and for allowing extra instrumentation.

CouchbaseMock is implemented in Java and is intended to be used by a single client instance. Testing with any real kind of workload has not been done, and it is not intended to be high performance or reliable (it does not even persist data to the disk). As opposed to cbgb, this is not intended to be a full implementation and/or replacement for the server.

The repository for CouchbaseMock may be found at https://github.com/couchbase/couchbasemock. This is a Maven project.

CouchbaseMock requires Java 8 or later at runtime. Java 9 or later is required when building the project from source.

Basic Usage

Typically, the mock is spawned by passing a --port argument as the REST port to listen on, and a list of bucket specifications separated by commas. Passing --help to the CouchbaseMock should show example usage. If no port is passed, it will listen on the REST port of 8091 (and will fail if you already have a Couchbase Server running).

By default, the mock will be up and running with the default bucket.

Once the mock has been started, it may be used like a normal Couchbase server, with clients bootstrapping over HTTP using the port specified as --port.

java -jar CouchbaseMock-1.5.27.jar --port 9000

and then in another console:

cbc cat foo -U http://localhost:9000

If you are using CouchbaseMock in automated testing, the test application should open up a control port, pass that port to the mock using the --harakiri-monitor argument and set --port to 0. The randomly assigned HTTP port will be received on the control port once. See the Out of Band Commands section below.

Supported Couchbase Operations

Memcached (Key-Value)

  • GET
  • GETQ
  • GAT
  • GATQ
  • TOUCH
  • SET
  • APPEND
  • PREPEND
  • REPLACE
  • ADD
  • REMOVE
  • INCR/DECR
  • GETL (From 0.6)
  • UNL (From 0.6)
  • OBSERVE (From 0.6)
  • GET_REPLICA (From 0.6)
  • STATS
  • VERSION
  • VERBOSITY

Administrative REST API

These standard REST API endpoints are supported. See the Couchbase Administration manual for how to use these endpoints. These behave exactly as they would against a real Couchbase cluster.

The username and password are hard-coded into the mock as Administrator and password respectively.

  • /pools (GET)
  • /pools/default (GET)
  • /pools/default/buckets (GET, POST) - allows for bucket creation
  • /pools/default/buckets/$bucket (GET, DELETE) - allows for bucket deletion
  • /pools/default/buckets/$bucket/ddocs (GET) - allows for listing design documents
  • /pools/default/bucketsStreaming/$bucket (GET) - streaming config URI
  • /sampleBuckets/install (POST) - allows loading the beer-sample bucket. Note that this endpoint seems to be undocumented.

Note that only SASL-auth buckets may be created. This does not necessarily mean that your bucket must have a password. For example:

curl -XPOST -u Administrator:password \
    localhost:8091/pools/default/buckets \
    -d bucketType=couchbase \
    -d name=newbucket \
    -d authType=sasl \
    -d ramQuotaMB=200

Will create a bucket without a password.

Additionally, note that the ramQuotaMB must be specified, though other than being necessary for conforming to server behavior, has no effect.

Views (Map-Reduce)

The following rest endpoints are supported. Note that the view query port (e.g. the capi port) is the same as the administrative port. This should not matter for conforming clients which determine this information from the cluster configuration endpoint.

Both map and reduce functions are supported. Javascript support is provided using Rhino, so view functions which depend on V8-specific functionality may fail.

The beer-sample bucket is available in the mock and may be loaded by passing the -S option on the commandline. It may also be loaded in-situ by using the /sampleBuckets/install REST API, for example:

curl -u Administrator:password localhost:8091/sampleBuckets/install \
    -X POST \
    -H "Content-Type: application/json" \
    -d '["beer-sample"]'

Accessing views may be done by the following endpoints:

  • /$bucket/_design/$ddoc (PUT, GET, DELETE) - used to create or remove design documents
  • /$bucket/_design/$ddoc/_view/$view - to query a view

The following view parameters are recognized and have effect

  • skip
  • limit
  • reduce
  • group
  • group_level
  • startkey
  • startkey_docid
  • endkey
  • endkey_docid
  • key
  • keys
  • inclusive_start (NOTE: not in Couchbase)
  • inclusive_end
  • descending
  • debug (returns dummy debug info)

The full_set and stale options are ignored.

Out-of-band Commands

The Out-Of-Band (OOB or Control) commands are where "special" commands can be sent to the mock to do certain things which can simulate different conditions.

OOBs are sent over the Harakiri Port. The Harakiri Port is a client-side listening port to which the mock will connect to once started up, and once the client close the connection the mock server will perform a harakiri. The normal "handshake" sequence is as follows:

Note that this can be found in tests/server.c in the libcouchbase distribution

  1. The client sets up a listening address (typically on a random port -- i.e. passing 0 for sin_port).
  2. Call the usual functions, i.e. socket(), bind(), and listen(). Then call getsockname() to get the newly assigned port number
  3. Invoke the CouchbaseMock JAR passing the newly assigned listening port as the argument to the --harakiri-monitor option, so e.g. --harakiri-monitor=localhost:42464
  4. Additionally, pass --port=0 to the JAR so that it will generate a random REST port (this way we don't have port conflicts)
  5. In the client, call accept() on the harakiri port. The mock will connect to it.
  6. Read from the new connection until an ASCII NUL is encountered. The data read will be a C string containing the ASCII representation of the newly assigned REST port.
  7. Once the REST port has been received, you can use it in normal Couchbase/lcb_t operation to connect to the mock cluster.
  8. Send/Receive additional OOB commands on the new harakiri connection established between client and mock

Command Format

The command format consists of JSON objects delimited by newlines. The JSON object will consist of the following keys.

  • command: this is the name of the command
  • payload: This is an object which contains the payload for the command

The response for the command will be delivered at its most basic level will be a JSON object consisting of the following fields

  • status: This indicates the status of the command, it will be "ok" if the command was successful
  • payload: (optional) - if there is more than a status to deliver

HTTP API

This is a lightweight API following the semantics of the JSON API; only that it uses HTTP as the transport.

The format of each command is http://localhost:18091/mock/<command>?payload\_param1=payload\_value1&...

Where is the value for the JSON command field, and the query parameters are expanded (URL-Encoded) fields within the payload.

Note that all requests (even those which modify data) use the GET method; this is to make it simple to test using a web browser.

Command Listings

The following commands are supported by the Mock. The payload for each command should contain dictionary keys corresponding to the listed Name of the parameter, and its value should conform to the specified Type.

failover

This command fails over a specific server with a given index (the index is obtained from the REST configuration). It may also be passed a bucket for which the failover should affect (if no bucket is passed, it will be default). Names in bold are required

Parameters:

Name Meaning Type
idx The server index JSON Number
bucket The bucket to affect (`"default"`) if unspecified JSON String

respawn

This command does the opposite of failover. Call this with the same arguments as failover to re-activate the node which was failed over.

hiccup

Schedules an artificial delay after a memcached server has sent a specific amount of data. This is intended to simulate a scenario where a server hangs or stalls after sending out a partial packet.

Parameters:

<tr>
    <td><b>msecs</b></td>
    <td>The duration of the delay in milliseconds</td>
    <td>JSON Number</td>
</tr>
<tr>
    <td><b>offset</b></td>
    <td>Stall after this many bytes have been sent</td>
    <td>JSON Number</td>
</tr>
Name Meaning Type

Setting both parameters to 0 disables hiccup

truncate

Chops off data from the end of each packet. As a result it means invalid data will be sent to the client (this may also be used in conjunction with failover to simulate a node sending partial data and then disconnecting)

Parameters:

Name Meaning Type
limit Limit the next write operation to this many bytes JSON Number

Setting the limit to 0 disables truncate

OpFail

Causes a number of memcached operations to unconditionally fail with a specific error code. This may be used to simulate simple 'OOM' or NOT_MY_VBUCKET errors.

Paramters:

Name Meaning Type
code The Memcached protocol code to force JSON Number; Must also be recognized by the Mock
count The number of times this error code should be sent before normal operation is restored. This can be either a positive number (which indicates that this many operations should fail before restoring to normal operation), 0 (which means that normal behavior be restored immediately) or a negative number, in which case commands will fail indefinitely until a 0 is sent again with this command JSON Number
servers A list of servers to apply this setting to. Servers are specified as indices into the server array. By default, all servers are used JSON Number

Time Travel

This command moves the internal clock in the server. The primary purpose for this is to allow the clients to test TTL without having to "sleep". Names in bold are required

Parameters:

Name Meaning Type
Offset The number of seconds to add to the internal clock JSON Number

SET_CCCP

This command enables or disables CCCP protocol semantics for a group of servers.

Parameters:

Name Meaning Type
enabled Whether to enable or disabled CCCP on the selection criteria JSON Boolean
bucket Bucket for which CCCP should be enabled/disabled. If this is empty, then this command affects all buckets String
servers An array of server indices for which the enable/disable setting should apply to. If this is not set, then all servers are modified Array of numbers

SET_ENHANCED_ERRORS

This command enables or disables Enhanced Error Messages semantics for a group of servers. See SDK-RFC-28 for details.

Parameters:

Name Meaning Type
enabled Whether to enable or disabled Enhanced Errors on the selection criteria JSON Boolean
bucket Bucket for which Enhanced Errors should be enabled/disabled. If this is empty, then this command affects all buckets String
servers An array of server indices for which the enable/disable setting should apply to. If this is not set, then all servers are modified Array of numbers

SET_COMPRESSION

This command sets compression mode for the group of servers. See SDK-RFC-30 for details.

Parameters:

Name Meaning Type
mode Operating mode for the server: "off", "passive", "active" (see spec for details). It also has extra mode "disabled", which makes mock to behave like it does not know Snappy at all. String
bucket Bucket for which Enhanced Errors should be enabled/disabled. If this is empty, then this command affects all buckets String
servers An array of server indices for which the enable/disable setting should apply to. If this is not set, then all servers are modified Array of numbers

GET_MCPORTS

This is a more convenient way to get the memcached ports without parsing the entire vBucket config. This is particularly useful for libcouchbase' tests which at the time of writing don't have access to a simple HTTP implementation

Parameters:

Name Meaning Type
bucket Which bucket to use. If unspecified, default is used string

The response shall contain in the payload field a JSON array of integers containing port numbers (relative to the Mock's listening addresses) which may be used as memcached ports.

keyinfo

This command returns the information about a given key in the mock server. Names in bold are required

Parameters:

Name Meaning Type
key The key to access JSON String
Bucket The bucket in which the key resides Optional. String. If not specified,
"default"
is used

The payload contains a JSON object containing the per-node status of a given key. The base object is a JSON array ([]). Each element in the array is a JSON object containing three fields.

The nodes are ordered according to the server list received in the vBucket configuration.

If the server is neither a replica nor a master for the given key, it is present as null.

  • Conf: Configuration information about this node in relation to the keys' vBucket. This is a JSON object containing two subfields:

    • Index - the server index in the vBucket map for the given vBucket. If this is a master, the index will be 0
    • Type - Either master or replica
  • Cache: This is a JSON object containing the status of the key as it resides in the node's Cache. If the item is not present within the node's cache, the object is empty; otherwise it contains these subfields:

    • CAS The CAS value of the key as present within the storage domain
    • Value the actual value of the key
  • Disk: This carries the same semantics as Cache, only that it displays information relating to the node's Disk storage domain.

Key Access Commands

Concepts

Starting with 0.6, the Mock introduces actual storage layers to emulate those of an actual cluster. Specifically, a cluster has one or more nodes, where each node retains a key in both its volatile memory (Cache) and persistent storage (Disk). While from a user perspective this process tends to be transparent, the distinction makes itself known when operating on things such as views (where indices are built from "persisted" items only) and the various OBSERVE and/or durability/persistence-requirement commands as well as get-from-replica.

Note that Cache and Disk represent abstract concepts in the Mock. At the time of writing, the Mock does not actually write anything to the disk, but merely contains a separate storage domain for "Disk".

Thus, whenever an item is stored in the mock it may go through the following steps:

  1. The item is inserted into the vBucket master's Cache
  2. The item is inserted into the vBucket master's Disk
  3. For each vBucket replica, the item is placed inside its Cache
  4. For each vBucket replica, the item is placed inside its Disk

Common Parameters

These out-of-band commands allow to modify or retrieve information on a specific key.

They all accept a set of common parameters

Name Meaning Type
Key The key to access JSON String
OnMaster Whether to affect the key on the vBucket master JSON Boolean
OnReplicas Which replicas should be affected This can either be a number indicating how many replicas to affect; or it can be a list of specific replica indices to affect
CAS The new CAS to use Optional. Number. If not specified, the existing CAS (if the key already exists) of each key entry in its respective storage partition will be used. Otherwise, a new CAS is generated
Value The new value to use Optional. String. If not specified the items value will be an empty string
Bucket The bucket in which the key resides Optional. String. If not specified,
"default"
is used

Below is a list of commands which accept these common parameters

Commands

persist

This command will store an item to one or more nodes' Disk storage domain. The nodes affected depend on the OnMaster and OnReplicas parameters

unpersist

Remove an item from the Disk storage domain from the selected nodes

cache

Store an item to one or more nodes' Cache

uncache

Remove an item from one or more nodes' Cache

endure

For each affected node, store the item to its Disk and Cache stores. This is equivalent to calling persist and cache on the same item

purge

For each affected node, remove the item from both its Disk and Cache stores. This is equivalent to calling uncache and unpersist on the same item

Retry Verification Commands

The mock can verify whether a client library is properly retrying commands. To use this feature, your client must have the XERROR feature enabled and implemented.

The usage overview is this:

  1. Setup retry verification recording before running your test
  2. Instruct the mock to inject failures (using the OPFAIL command), which will trigger the retry. Note that you can inject failures using other means as well (e.g. internally at the client level)
  3. Execute your operations with failure injection enabled (per step 2)
  4. Once the operations are done, request the mock to verify behavior. This will also implicitly undo whatever setup was done in step 1.

You can set up retry verification using the START_RETRY_VERIFY command. This command requires the server index and the bucket name to use for verification.

Because the precise server index must be known, you will need to determine the vBucket for the key that will be used in the commands.

# Pseudo code
test_key = "HelloWorld"
vbucket = vbucket_map(test_key)
server = server_map(vbucket)

In order to trigger the correct error retry behavior, you will need to use special error return codes which are further defined in the Mock itself. If the client is properly implemented and functioning correctly, it should not have explicit knowledge of these error codes - but should be handled dynamically by using the corresponding entry in the error map.

The error codes are:

  • 0x7ff0 - defines a constant retry strategy
  • 0x7ff1 - defines a linear retry strategy
  • 0x7ff2 - defines an exponential retry strategy.

You should test with all three error codes to verify that the client can correctly handle all three strategies.

Then set up the OPFAIL command to be directed towards the correct server:

cmd = {
    'command': 'OPFAIL',
    'payload': {
        'servers': [server],
        'bucket': 'default',
        'count': 100,
        'code': 0x7ff1
    }
}

And then set up the START_RETRY_VERIFY command.

cmd = {
    'command': 'START_RETRY_VERIFY',
    'payload': {
        'idx': server,  # Numeric index of server
        'bucket': 'default'
    }
}

Note that START_RETRY_VERIFY only tells the server to start recording command logs.

Once the OPFAIL is sent, any command directed to the specified servers will cause the server to return the error code specified. For the purposes of testing, a simple GET (0x00) command should suffice to trigger the error behavior.

The command should eventually fail on the client side - after multiple internal retries by the client.

Once the client has failed the command, you should query the mock to determine if the client had behaved as expected. This is done using the CHECK_RETRY_VERIFY command.

The CHECK_RETRY_VERIFY command requires the server index (from above), the error, and the opcode of the test operation. If verification succeeded, the command will return success, and if it failed, it will return an error with some additional information.

The format of CHECK_RETRY_VERIFY is:

'command': {
    'payload': {
        'idx': server,
        'bucket': 'default',
        'errcode': 0x7ff1,
        'opcode': 0x00
    }
}

The mock uses three basic tests to determine if the retries were done according to spec.

  1. The first retry should be within after (+/- fuzz) ms of the first error response.
  2. The spacing between each interval should be as prescribed (strategy dependent)
  3. The last retry should not exceed past (+/- fuzz) ms of the max-duration interval from the receipt of the first error.

The "fuzz" is defined as 10ms. Fuzz is required because not all operating environments (virtual machines, interpreters, clocks, etc.) can guarantee accuracy/resolution within 1 ms.

In the following example, conformance to the constant strategy is verified. We will assume that the clock begins at 0 ms

Here is the spec:

{
    "strategy": "constant",
    "max-duration": 500,
    "interval": 10,
    "after": 50
}
  • 0ms: Client receives error response
  • 53ms: After waiting ~50ms, the client sends the first retry. This should be within fuzz+after of first error response.
  • 60ms: After waiting ~10ms, the client sends the next retry. This should be within fuzz+interval of the previous retry attempt.
  • 69ms: Retry
  • 75ms: Retry ....
  • 484ms: Client sends retry...
  • 497ms: Client sends last retry. Should be within interval+fuzz of +500ms (Time since first error response)

Verifying this with linear or exponential retries is similar. Here's an example for linear retry:

{
    "strategy": "linear",
    "max-duration": 500,
    "interval": 10,
    "after": 50,
    "ceil": 200
}
  • 0ms: Client receives error response
  • 55ms: Client sends first retry
  • 62ms: Client sends next retry (interval is 10ms)
  • 87ms: Client sends next retry (interval is now 20ms)
  • 109ms: Client sends next retry (interval is now 30ms)
  • 142ms: Client sends next retry (interval is now 40ms)
  • 195ms: Client sends next retry (interval is now 50ms)
  • 256ms: Client sends next retry (interval is now 60ms) ...

couchbasemock's People

Contributors

aloren avatar avsej avatar bsubhashni avatar chvck avatar daschl avatar dnault avatar ingenthr avatar jimhooker2002 avatar magro avatar majecty avatar mikegoldsmith avatar mnunberg avatar randomanderson avatar trondn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

couchbasemock's Issues

ENOENT for GET for doc created using increment/decrement

When creating a document using the increment/decrement commands a later GET appears to be unable to locate the document with ENOENT. This appears to be working correctly against an actual server. Subsequent increment/decrements for the same appear to also work against Mock though.

MemcachedServers created by CouchbaseMock not working?

Hi,

I'm just checking out CouchbaseMock as it seems to be useful for integration testing. Unfortunately I don't get it to work when I'm running a simple test with spymemcached (2.7.3), a stored (set) value is null when requested (get) afterwards.

This is the test I'm running:

public static void main(final String[] args) throws IOException, URISyntaxException, InterruptedException, ExecutionException {
    final CouchbaseMock instance = new CouchbaseMock("localhost", 18091, 1, 1);
    final Thread thread = new Thread(instance);
    thread.start();
    Thread.sleep(500);
    MemcachedClient mc = null;
    try {
        final URI base = new URI("http://localhost:18091/pools");
        mc = new MemcachedClient(Arrays.asList(base), "default", "");

        final Boolean setResult = mc.set("hello", 1000, "world").get();
        System.out.println("Result from set: " + setResult);
        final String result = (String) mc.get("hello");
        System.out.println("Got hello " + result);
    } finally {
        System.out.println("Stopping services...");
        mc.shutdown();
        thread.interrupt();
        instance.close();
    }
}

This results in the following output:

2011-10-17 01:05:58.625 INFO net.spy.memcached.MemcachedConnection:  Added {QA sa=localhost/127.0.0.1:60034, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2011-10-17 01:05:58.757 INFO net.spy.memcached.MemcachedConnection:  Connection state changed for sun.nio.ch.SelectionKeyImpl@4e99353f
Result from set: true
Got hello null
Stopping services...
2011-10-17 01:05:58.775 INFO net.spy.memcached.MemcachedClient:  Shut down memcached client
Exception in thread "Thread-0" java.nio.channels.ClosedSelectorException
    at sun.nio.ch.SelectorImpl.selectedKeys(SelectorImpl.java:57)
    at org.couchbase.mock.http.HttpServer.serve(HttpServer.java:81)
    at org.couchbase.mock.CouchbaseMock.run(CouchbaseMock.java:486)
    at java.lang.Thread.run(Thread.java:662)

I also tried starting the MemcachedServer created by CouchbaseMock (by invoking MemcachedServer.startup), but this does not fix it.

Is there anything else to do to be able to actually use the created MemcachedServers?

Thanx && cheers,
Martin

Wrong subdoc error returned on dict add for array path

When a dict add is performed on an array path the server returns with SUBDOC_PATH_INVALID while the mock responds with SUBDOC_PATH_EXISTS.

    @Test
    public void shouldReturnPathInvalidOnDictAddForArrayPath() {
        String subPath = "sub.array[1]";
        ByteBuf fragment = Unpooled.copiedBuffer("\"insertedPath\"", CharsetUtil.UTF_8);
        ReferenceCountUtil.releaseLater(fragment);

        //mutate
        SubDictAddRequest insertRequest = new SubDictAddRequest(testSubKey, subPath, fragment, bucket());
        assertFalse(insertRequest.createIntermediaryPath());

        SimpleSubdocResponse insertResponse = cluster().<SimpleSubdocResponse>send(insertRequest).toBlocking().single();
        ReferenceCountUtil.releaseLater(insertResponse.content());
        assertFalse(insertResponse.status().isSuccess());
        assertEquals(0, insertResponse.content().readableBytes());
        assertEquals(ResponseStatus.SUBDOC_PATH_INVALID, insertResponse.status());
    }

Query always returns empty response because of incorrect pattern registration

There are a couple of issues already filed around this bug ( #35, #54 ). I found the root cause so maybe these can all be merged together.

Couchbase sends the post request for queries to /query. Unfortunately, at

httpServer.register("/query/*", new QueryServer());
the mock registers using /query/*. These patterns do not match so the response is always empty.

Import Script

It would be great if I could run a script that just imports the design documents (not even documents but that would be nice) into CouchbaseMock... is there any existing tool for this, or it entirely manual?

Mock does not fail with invalid cas on append and prepend

Hi,

java-client has a test that looks like this:

    @Test(expected = CASMismatchException.class)
    public void shouldFailWithInvalidCASOnAppend() {
        assumeFalse(CouchbaseTestContext.isMockEnabled());

        StringDocument stored = bucket().upsert(StringDocument.create("appendCasMismatch", "foo"));
        bucket().append(StringDocument.from(stored, stored.cas() + 1));
    }

    @Test(expected = CASMismatchException.class)
    public void shouldFailWithInvalidCASOnPrepend() {
        assumeFalse(CouchbaseTestContext.isMockEnabled());

        StringDocument stored = bucket().upsert(StringDocument.create("prependCasMismatch", "foo"));
        bucket().prepend(StringDocument.from(stored, stored.cas() + 1));
    }

So we make sure that if an append or prepend is called with the wrong cas after the upsert, the server fails with a cas mismatch - the mock should too!

"Partition size is not equal after conversion, this is a bug"

Hi there,

I've been trying to setup couchbaseMock on my local machine and I have an issue when the client tries to connect with the bucket which is the "Partition size is not equal after conversion, this is a bug".

I've noticed that the bucket I've created on the mock cluster is of the type "membase" even though I've created with the type "couchbase". Could it be related to the issue above?

Is there anything I'm missing here?

More details below:

The error

Caused by: com.couchbase.client.core.config.ConfigurationException: Could not open bucket.
..
Caused by: com.couchbase.client.core.CouchbaseException: Could not parse configuration
..
Caused by: com.couchbase.client.deps.com.fasterxml.jackson.databind.JsonMappingException: Instantiation of [simple type, class com.couchbase.client.core.config.DefaultCouchbaseBucketConfig] value failed: Partition size is not equal after conversion, this is a bug.

Command used to setup the bucket

curl -XPOST -u Administrator:password     localhost:8091/pools/default/buckets     -d bucketType=couchbase     -d name=api-booking     -d authType=sasl     -d ramQuotaMB=200 

Command to get details of the bucket created

url -u Administrator:password     localhost:8091/pools/default/buckets/api-booking
{"bucketType":"membase", }

Regards,

Impossible to connect to a mock with multiple nodes

couchbase-client-impl.zip
Hello
I currently work on the test of my application with the CouchbaseMock
The version of the couchabse mock is 1.5.25
The version of the Couchbase Java SDK is 3.0.5
When I setup the mock with 1 nodes all works not problem.
But with the same code when I setup 10 nodes with replica of 2 i hava a connection failure

com.couchbase.client.core.error.AmbiguousTimeoutException: InsertRequest {"cancelled":true,"completed":true,"coreId":"0x7215aed700000001","idempotent":false,"lastChannelId":"7215AED700000001/00000000F203E8CA","lastDispatchedFrom":"127.0.0.1:62173","lastDispatchedTo":"localhost:62143","reason":"TIMEOUT","requestId":10,"requestType":"InsertRequest","retried":7,"retryReasons":["KV_NOT_MY_VBUCKET"],"service":{"bucket":"e66cfb62-0e33-49e4-a0b5-ca8b78d5eb01","collection":"_default","documentId":"fa712e81-c831-4fb4-8103-fc744d3c50ae","opaque":"0x13","scope":"_default","syncDurability":{"present":false},"type":"kv"},"timeoutMs":2500,"timings":{"dispatchMicros":1383,"encodingMicros":1566,"totalMicros":2508019}}
at com.couchbase.client.java.AsyncUtils.block(AsyncUtils.java:51)
at com.couchbase.client.java.Collection.insert(Collection.java:381)
at com.amadeus.datastore.nosql.couchbase.impl.KeyValueKoTest.insertAndGet(KeyValueKoTest.java:52)

In attachement you can find a reproducer with the two scenario :
KeyValueKoTest that failed
KeyValueTest that success
couchbase-client-impl.zip

I made some other test with the same code on real couchbase cluster and it's works fine
Would it be possible to help me ?
Thanks

Can't open bucket with Couchbase Java SDK (2.1.2)

When I trying to connect to CouchbaseMock in my porject, TimeoutException occurs. I can find Couchbase client trying to connect to 11210port . But CouchbaseMock do not seems to open 11210 port (I check with netstat -an | grep LISTEN) Is there the way to use CouchbaseMock with lastest version of java sdk?

Code (I embeded CouchbaseMock on my project):

BucketConfiguration bucketConfiguration = new BucketConfiguration();
bucketConfiguration.numNodes = 10;
bucketConfiguration.numReplicas = 3;
bucketConfiguration.name = "default";
bucketConfiguration.type = Bucket.BucketType.COUCHBASE;
bucketConfiguration.password = "";

ArrayList<BucketConfiguration> configList = new ArrayList<>();
configList.add(bucketConfiguration);
CouchbaseMock couchbaseMock = new CouchbaseMock(0, configList);
couchbaseMock.start();
couchbaseMock.waitForStartup();


MockClient mockClient = new MockClient(new InetSocketAddress("localhost", 8092));
couchbaseMock.startHarakiriMonitor("localhost:" + mockClient.getPort(), false);
mockClient.negotiate();

DefaultCouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().build();
CouchbaseCluster cluster = CouchbaseCluster.create(env, Lists.newArrayList("127.0.0.1"));

// TimeoutException occurs on following statement:
cluster.openBucket("bucket");

StackTrance of the exception:

Exception in thread "main" java.lang.RuntimeException: java.util.concurrent.TimeoutException
    at com.couchbase.client.java.util.Blocking.blockForSingle(Blocking.java:93)
    at com.couchbase.client.java.CouchbaseCluster.openBucket(CouchbaseCluster.java:108)
    at com.couchbase.client.java.CouchbaseCluster.openBucket(CouchbaseCluster.java:99)
    at com.couchbase.client.java.CouchbaseCluster.openBucket(CouchbaseCluster.java:89)
    at com.couchbase.client.java.CouchbaseCluster.openBucket(CouchbaseCluster.java:79)
    at kr.co.vcnc.fearow.CouchbaseMockMain.main(CouchbaseMockMain.java:52)
Caused by: java.util.concurrent.TimeoutException
    ... 6 more

StackTrace that logged by couchbase-client:

[WARN][Endpoint][cb-io-1-1] [null][KeyValueEndpoint]: Could not connect to endpoint, retrying with delay 32 MILLISECONDS: 
java.net.ConnectException: Connection refused: localhost/127.0.0.1:11210
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:716)
    at com.couchbase.client.deps.io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:208)
    at com.couchbase.client.deps.io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:281)
    at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:528)
    at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
    at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
    at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
    at com.couchbase.client.deps.io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
    at com.couchbase.client.deps.io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
    at java.lang.Thread.run(Thread.java:745)

i sumit this issue on Couchbase forum, but I also create issue on the repo.

Not My Vbucket with 2 nodes and 1 replica

While implementing replica get and testing with the mock, I noticed an issue which comes up depending on the key. When configured with 2 nodes and 1 replica, I get NMVs for the active node both for upsert and get. See this simple example:

String id = "4c03805d-adc9-47a7-9014-bd94c693a2bb";
collection.upsert(id, "Hello, World!");
Thread.sleep(1000);
collection.get(id);

I am not sure what is causing this, but my code seems to work against a real cluster. Maybe it has something to do with how the mock handles its config/topo?

Query views returning empty response in SDK 2.5.9

Hi,

Currently we are integrating the Couchbase Mock with couchbase client SDK 2.5.9.

Our current problem are in the view query, the couchbase sdk are always returning empty results
There are any know issue, for sdk 2.x ?

Best regards

RFC: Explicit Embedded Mode Support

Just wanted to contribute the following for discussion. As argued in #16 (see my comments on the ticket towards the bottom) I'd love to see "embedded" mode, explicitly supported as part of this project.

I sketched out the following jimhooker2002/CouchbaseMock@master...embedded-support-proto

I'd love to get some comments/thoughts on the idea. Is it worth me spending a bit of time sketching out the rest of that class (production quality/tests/documentation etc)? Philosophically, is it clear what I'm trying to do here, and do you guys agree it's a good idea? Of course, if you don't agree that this is useful, then there's no point me spending a bunch of time on it.

As mentioned in the comments of the diff - the existing client code that we have to talk with HarikiriMonitor over a socket/HTTP makes perfect sense when running in a seperate process. But, when running in embedded mode (same process as test code) it's a nicer experience to just do "regular Java stuff" with the CouchbaseMock object itself - no network/REST/socket interaction, and the usage of Java types as opposed to the raw JSON.

All the best,

Jim.

Test couchbase v3 client exists command doesn't work

When I test
bucket.defaultCollection().exists(id);
in couchbase v3 API,
It will return UNKNOWN command error

GetMetaRequest failed with unexpected status code UNKNOWN
com.couchbase.client.core.error.CouchbaseException: GetMetaRequest failed with unexpected status code UNKNOWN {"completed":true,"coreId":"0x79feb7be00000001","idempotent":true,"lastChannelId":"79FEB7BE00000001/000000003CB70CF2","lastDispatchedFrom":"127.0.0.1:55345","lastDispatchedTo":"localhost:55340","requestId":10,"requestType":"GetMetaRequest","retried":0,"service":{"bucket":"inventory","collection":"_default","documentId":"test","opaque":"0x12","scope":"_default","type":"kv"},"status":"UNKNOWN","timeoutMs":2500,"timings":{"dispatchMicros":1965,"totalMicros":9548,"serverMicros":0}}

and I compare with client v2, it used the OBSERVE command before
but in v3, it uses the EXISTS command

Is it possible to provide a client v3 example also?

Thanks

Subdoc does not return error for e2big

Hi,

the java-client has a couple of datastructures test that assert that when a subdoc op is performed with content bigger than 20mb it will not return a E2BIG like the server does.

Question about development testing

Hello.

So I use mySQL and Couchbase Server for my application.

I want to test the application server locally in an easy to initialise manner, with as little overhead as possible.

For mySQL, I just point my server's adapter to a SQLite file.

Can I expect CouchbaseMock (I get it doesn't support N1QL) to be the SQLite equivalent for this purpose?

Feature Request: N1QL Support

I'm thinking about the following:

1: We can take a bit of inspiration from the design/structure/tooling of https://github.com/JSQLParser/JSqlParser to give us a "base" for this feature.

2: We can lift/reuse (and then tweak) the .ebnf/.y/.nex files from here: https://github.com/couchbase/query/ to give us the grammar we need.

Our mock implementation of the planner/executor would obviously be a very stripped down and simplified version.

In summary - lift the grammar from couchbase/query, then build much simplified versions of the planner/executor etc.

Thoughts? Any other ideas around how we can get a N1QL support in the mock?

Properly shade third party dependencies

For some reason that I don't understand, this project repackages gson and a bunch of other libraries.

This prevents CouchbaseMock to be integrated in Spring Boot. If you decide to go with a one-jar only solution, please shade those libs so that they end up in a different package.

Default value for inclusive_end is incorrect based on the Couchbase 3.0 documentation

It looks like the default value for inclusive_end is incorrect in Couchbase Mock. Based on the documentation it looks like inclusive_end should be set to true.

http://docs.couchbase.com/admin/admin/Views/views-querying.html

I have confirmed this by running a test against a real Couchbase instance. The mock server doesn't return my view query result when the key matches the end key, but the result is returned on the real instance.

Mock returns 0 on binary delete

When a document is deleted, the mock returns a 0 cas but the server does not (which for example is used for durability requirements on observe after a delete)

Release

Hello

Great project that might be very useful for integration testing. However without any releases it will be hard to convince my superiors to integrate it in our project.

Are you planning to release it on maven central ?

Thank you
Alexander KIRILOV

Support macro expansion / xattr

Hi,

one example failed against the mock: I'm trying to cover the case "get with expiration" so it would have to fall back to subdoc. I do a XATTR GET to $document.exptime combined with a GET_DOC which would give me all I need... this works fine against a real server but fails against the mock.

I assume it is because the mock is missing xattr/macro expansions?

CouchbaseMock doesn't work with the latest Couchbase

Hi,

I'm currently working on the test of my application with CouchbaseMock in the following context: CouchbaseMock 1.5.25 and Couchbase Java SDK is 3.0.10.

Establishing a connection to the bucket, for every transaction (different from an upsert) the mock engine give me the following errors in console:

java.util.concurrent.TimeoutException: Did not observe any item or terminal signal within 10000ms in 'source(MonoDefer)' (and no fallback has been configured) 

The timeout of 10s occurs in every request (as a WARNING) except upsert.

For every operation, for instance count, I get a FeatureNotAvailableException:

com.couchbase.client.core.error.FeatureNotAvailableException: The cluster does not support cluster-level queries (only Couchbase Server 6.5 and later) and no bucket is open. If an older Couchbase Server version is used, at least one bucket needs to be opened to dispatch this query request!
at com.couchbase.client.core.error.FeatureNotAvailableException.clusterLevelQuery(FeatureNotAvailableException.java:41)

Doing the same test with the previous Couchbase version, everything works fine.

Is there any way to mock the new SDK?

Thanks

Touch does not change the cas

When the ttl on a document is changed, the server also changes the cas - based on my tests I think the mock does not .. Similar to the getAndLock issue maybe?

Wrong Subdoc Error returned on counter underflow

When a counter underflow is triggered, the real server responds with SUBDOC_DELTA_RANGE while the mock responds with SUBDOC_VALUE_CANTINSERT.

Here is the test case from core-io that triggers it:

    @Test
    public void shouldReturnDeltaRangeOnCounterDeltaUnderflow() {
        String path = "counter";
        long prepareUnderflow = -1L;
        long delta = Long.MIN_VALUE;

        //first request will bring the value to -1
        SubCounterRequest request = new SubCounterRequest(testSubKey, path, prepareUnderflow, bucket());
        SimpleSubdocResponse response = cluster().<SimpleSubdocResponse>send(request).toBlocking().single();
        ReferenceCountUtil.releaseLater(response.content());
        String result = response.content().toString(CharsetUtil.UTF_8);

        assertEquals("-1", result);

        //second request will underflow
        request = new SubCounterRequest(testSubKey, path, delta, bucket());
        response = cluster().<SimpleSubdocResponse>send(request).toBlocking().single();
        ReferenceCountUtil.releaseLater(response.content());
        result = response.content().toString(CharsetUtil.UTF_8);

        assertEquals(result, 0, result.length());
        assertEquals(ResponseStatus.SUBDOC_DELTA_RANGE, response.status());
    }

MockResponse.isOk can fail with NPE

If couchbase operation failed, isOk should return false, but instead it throws NPE.
isOk method should check for 'status' field presence as getErrorMessage for 'error' does.

java.lang.NullPointerException: null
    at org.couchbase.mock.client.MockResponse.isOk(MockResponse.java:33)

N1QL support

Hi,

I'm using the CouchbaseMock to do the unit test where a Couchbase client will send a N1QL query to the mock server. But it turns out that the client cannot decode the result which is null.

Here is my N1QL query:

SELECT * FROM scientists``

And here is the trace:

java.lang.IndexOutOfBoundsException: readerIndex(0) + length(1) exceeds writerIndex(0): PooledUnsafeDirectByteBuf(ridx: 0, widx: 0, cap: 256) com.couchbase.client.core.CouchbaseException: java.lang.IndexOutOfBoundsException: readerIndex(0) + length(1) exceeds writerIndex(0): PooledUnsafeDirectByteBuf(ridx: 0, widx: 0, cap: 256) at com.couchbase.client.core.endpoint.AbstractGenericHandler.decode(AbstractGenericHandler.java:369) at com.couchbase.client.deps.io.netty.handler.codec.MessageToMessageCodec$2.decode(MessageToMessageCodec.java:81) at com.couchbase.client.deps.io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:88) at com.couchbase.client.deps.io.netty.handler.codec.MessageToMessageCodec.channelRead(MessageToMessageCodec.java:111) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:356) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:342) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:335) at com.couchbase.client.deps.io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:438) at com.couchbase.client.deps.io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:312) at com.couchbase.client.deps.io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:286) at com.couchbase.client.deps.io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:253) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:356) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:342) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:335) at com.couchbase.client.deps.io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:286) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:356) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:342) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:335) at com.couchbase.client.deps.io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1304) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:356) at com.couchbase.client.deps.io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:342) at com.couchbase.client.deps.io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:921) at com.couchbase.client.deps.io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:135) at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:646) at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:581) at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:498) at com.couchbase.client.deps.io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:460) at com.couchbase.client.deps.io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:131) at com.couchbase.client.deps.io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.IndexOutOfBoundsException: readerIndex(0) + length(1) exceeds writerIndex(0): PooledUnsafeDirectByteBuf(ridx: 0, widx: 0, cap: 256) at com.couchbase.client.deps.io.netty.buffer.AbstractByteBuf.checkReadableBytes0(AbstractByteBuf.java:1161) at com.couchbase.client.deps.io.netty.buffer.AbstractByteBuf.readByte(AbstractByteBuf.java:591) at com.couchbase.client.core.utils.yasjl.ByteBufJsonParser.readNextChar(ByteBufJsonParser.java:458) at com.couchbase.client.core.utils.yasjl.ByteBufJsonParser.parse(ByteBufJsonParser.java:109) at com.couchbase.client.core.endpoint.query.parser.YasjlQueryResponseParser.parse(YasjlQueryResponseParser.java:337) at com.couchbase.client.core.endpoint.query.QueryHandlerV2.decodeResponse(QueryHandlerV2.java:175) at com.couchbase.client.core.endpoint.query.QueryHandlerV2.decodeResponse(QueryHandlerV2.java:62) at com.couchbase.client.core.endpoint.AbstractGenericHandler.decode(AbstractGenericHandler.java:338) ... 29 more

I have tested the N1QL on a real Couchbase server and it worked well. Could any one help me out? Thanks

Regards,
Guobao

Tests fail, can't make this work


T E S T S

Running org.couchbase.mock.BucketSpecTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.114 sec
Running org.couchbase.mock.CacheBucketTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.097 sec
Running org.couchbase.mock.client.ClientTest
Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.264 sec
Running org.couchbase.mock.client.MockAPITest
Tests run: 16, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.287 sec
Running org.couchbase.mock.client.SaslAuthTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.003 sec
Running org.couchbase.mock.http.PoolsHandlerTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running org.couchbase.mock.JMembaseTest
Tests run: 16, Failures: 10, Errors: 1, Skipped: 0, Time elapsed: 1.834 sec <<< FAILURE!
testHandleHttpRequest(org.couchbase.mock.JMembaseTest) Time elapsed: 0.105 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<200> but was:<404>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testHandleHttpRequest(JMembaseTest.java:114)

testHandleHttpRequestWithTrailingSlash(org.couchbase.mock.JMembaseTest) Time elapsed: 0.106 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<200> but was:<404>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testHandleHttpRequestWithTrailingSlash(JMembaseTest.java:128)

testAdministratorCouldAccessProtectedBuckets(org.couchbase.mock.JMembaseTest) Time elapsed: 0.106 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<200> but was:<404>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testAdministratorCouldAccessProtectedBuckets(JMembaseTest.java:142)

testDefaultBucketShouldBeAccessibleForEveryone(org.couchbase.mock.JMembaseTest) Time elapsed: 0.107 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<200> but was:<404>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testDefaultBucketShouldBeAccessibleForEveryone(JMembaseTest.java:155)

testProtectedBucketsShouldBeFilteredOutFromList(org.couchbase.mock.JMembaseTest) Time elapsed: 0.152 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<1> but was:<3>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testProtectedBucketsShouldBeFilteredOutFromList(JMembaseTest.java:176)

testHandleHttpRequestMissingAuth(org.couchbase.mock.JMembaseTest) Time elapsed: 0.106 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<401> but was:<404>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testHandleHttpRequestMissingAuth(JMembaseTest.java:219)

testHandleHttpRequestIncorrectCred(org.couchbase.mock.JMembaseTest) Time elapsed: 0.105 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<401> but was:<404>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testHandleHttpRequestIncorrectCred(JMembaseTest.java:234)

testHandleHttpRequestIllegalCred(org.couchbase.mock.JMembaseTest) Time elapsed: 0.105 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<401> but was:<404>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testHandleHttpRequestIllegalCred(JMembaseTest.java:250)

testHandleHttpRequestUnkownFile(org.couchbase.mock.JMembaseTest) Time elapsed: 0.113 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<404> but was:<200>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testHandleHttpRequestUnkownFile(JMembaseTest.java:265)

testConfigStreaming(org.couchbase.mock.JMembaseTest) Time elapsed: 0.114 sec <<< ERROR!
java.io.FileNotFoundException: http://localhost:28091/pools/default/bucketsStreaming/protected
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1457)
at org.couchbase.mock.JMembaseTest.testConfigStreaming(JMembaseTest.java:359)

testRestFlush(org.couchbase.mock.JMembaseTest) Time elapsed: 0.16 sec <<< FAILURE!
junit.framework.AssertionFailedError: expected:<200> but was:<404>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:282)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:201)
at junit.framework.Assert.assertEquals(Assert.java:207)
at org.couchbase.mock.JMembaseTest.testRestFlush(JMembaseTest.java:413)

Running org.couchbase.mock.MembaseBucketTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.044 sec
Running org.couchbase.mock.util.Base64Test
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running org.couchbase.mock.util.GetoptTest
Tests run: 18, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec

Results :

Failed tests: testHandleHttpRequest(org.couchbase.mock.JMembaseTest): expected:<200> but was:<404>
testHandleHttpRequestWithTrailingSlash(org.couchbase.mock.JMembaseTest): expected:<200> but was:<404>
testAdministratorCouldAccessProtectedBuckets(org.couchbase.mock.JMembaseTest): expected:<200> but was:<404>
testDefaultBucketShouldBeAccessibleForEveryone(org.couchbase.mock.JMembaseTest): expected:<200> but was:<404>
testProtectedBucketsShouldBeFilteredOutFromList(org.couchbase.mock.JMembaseTest): expected:<1> but was:<3>
testHandleHttpRequestMissingAuth(org.couchbase.mock.JMembaseTest): expected:<401> but was:<404>
testHandleHttpRequestIncorrectCred(org.couchbase.mock.JMembaseTest): expected:<401> but was:<404>
testHandleHttpRequestIllegalCred(org.couchbase.mock.JMembaseTest): expected:<401> but was:<404>
testHandleHttpRequestUnkownFile(org.couchbase.mock.JMembaseTest): expected:<404> but was:<200>
testRestFlush(org.couchbase.mock.JMembaseTest): expected:<200> but was:<404>

Tests in error:
testConfigStreaming(org.couchbase.mock.JMembaseTest): http://localhost:28091/pools/default/bucketsStreaming/protected

Tests run: 67, Failures: 10, Errors: 1, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.845 s
[INFO] Finished at: 2014-10-15T14:00:30-05:00
[INFO] Final Memory: 7M/81M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project CouchbaseMock: There are test failures.

Decrement lets counter go below zero

The server states and implements that the counter decrement cannot get the value below zero. The mock though lets it go into a negative range.

Reproduce recent stats behaviour

In MemcachedServer.java getStats, the Mock produces a stats key that doesn't seem to be supported any more ("tap").

I'm testing multikey responses from the Python SDK*, so I need two keys that are present in stats. I'm currently working around this by switching based on whether I'm using a Mock or not, as follows, so I'd suggest adding the 'config'='ep_dcp_conn_buffer_size' entry to the stats output:

second_entry = {True: {'tap': "ep_tap_count"}, False: {'config': "ep_dcp_conn_buffer_size"}}[self.is_mock]

*https://github.com/couchbase/couchbase-python-client/blob/bd3bcbba701b89910587eaa89f1793a8c328e8e0/couchbase/tests/cases/stats_t.py#L49-L57

Cannot create the primary index on the bucket, failed with timeoutexception

Hello,
I am encountering an issue while creating the primary index on the bucket.
Below are two ways that i tried to create the index, none of them work, all failed with TimeoutException.

SimpleN1qlQuery simple = N1qlQuery.simple("CREATE PRIMARY INDEX ON bucket");
N1qlQueryResult query = bucket.query(simple);

boolean primaryIndex = bucket.bucketManager().createN1qlPrimaryIndex(true, false);

without index, we cannot test the n1ql queries.

Any suggestions please ? thank you in advance

Invalid user can list buckets

Doing a GET /pools/default/buckets against CouchbaseMock succeeds even with an invalid username and password (though it does return a blank response). I believe this is is an error, and a 403 should be returned instead.

Publish to maven central

I can't find this project in maven central, please point me to the correct place or publish it to maven central.
Without this it won't take much traction as most of companies don't allow downloading artifacts from other repositories.

Setting expiry more than 30 days in the future fails on Mock

But, it works great on the server. The mock should add the doc, with the proper expiry. There is some tricky stuff here - if the expiry you set is less than 30 days worth of seconds from now, it is just that. If it is larger than that, it is assumed to be a date in seconds since 1/1/1970. And it is returned the same way.

GetAndTouch does not change the cas

While implementing getAndTouch tests I found that the server is bumping the cas value on getAndTouch (since the expiry changes), but the mock does not .. should this be fixed?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.