├── src ├── test │ ├── resources │ │ ├── report.zip │ │ └── test.yml │ └── java │ │ └── com │ │ └── blazemeter │ │ ├── api │ │ ├── exception │ │ │ ├── ValidationExceptionTest.java │ │ │ ├── InterruptRuntimeExceptionTest.java │ │ │ └── UnexpectedResponseExceptionTest.java │ │ ├── http │ │ │ ├── HttpLoggerTest.java │ │ │ ├── RetryInterceptorTest.java │ │ │ └── HttpUtilsTest.java │ │ ├── logging │ │ │ ├── UserNotifierTest.java │ │ │ ├── impl │ │ │ │ └── FileLoggerTest.java │ │ │ └── LoggerTest.java │ │ ├── utils │ │ │ ├── BlazeMeterUtilsSlowEmul.java │ │ │ ├── BlazeMeterUtilsEmul.java │ │ │ └── BlazeMeterUtilsTest.java │ │ └── explorer │ │ │ ├── base │ │ │ └── BZAObjectTest.java │ │ │ ├── UserTest.java │ │ │ ├── AccountTest.java │ │ │ ├── ProjectTest.java │ │ │ ├── test │ │ │ ├── AnonymousTestTest.java │ │ │ └── MultiTestTest.java │ │ │ ├── WorkspaceTest.java │ │ │ └── SessionTest.java │ │ └── ciworkflow │ │ └── TestsListFlowTest.java └── main │ └── java │ └── com │ └── blazemeter │ ├── api │ ├── exception │ │ ├── ValidationException.java │ │ ├── InterruptRuntimeException.java │ │ └── UnexpectedResponseException.java │ ├── http │ │ ├── RequestTask.java │ │ ├── HttpLogger.java │ │ ├── RetryInterceptor.java │ │ └── HttpUtils.java │ ├── logging │ │ ├── impl │ │ │ ├── LoggerImpl.java │ │ │ └── FileLogger.java │ │ ├── UserNotifier.java │ │ ├── Logger.java │ │ └── LoggerFormatter.java │ ├── explorer │ │ ├── test │ │ │ ├── ITest.java │ │ │ ├── AbstractTest.java │ │ │ ├── AnonymousTest.java │ │ │ ├── TestDetector.java │ │ │ ├── MultiTest.java │ │ │ └── SingleTest.java │ │ ├── User.java │ │ ├── base │ │ │ └── BZAObject.java │ │ ├── Account.java │ │ ├── Project.java │ │ ├── Session.java │ │ └── Workspace.java │ └── utils │ │ └── BlazeMeterUtils.java │ └── ciworkflow │ ├── BuildResult.java │ └── TestsListFlow.java ├── maven-central-deploy.sh ├── .gitignore ├── .travis.yml ├── settings.xml ├── Jenkinsfile ├── README.md └── pom.xml /src/test/resources/report.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Blazemeter/blazemeter-api-client/master/src/test/resources/report.zip -------------------------------------------------------------------------------- /maven-central-deploy.sh: -------------------------------------------------------------------------------- 1 | #! /bin/sh -xe 2 | 3 | mvn -Dmaven.test.skip=true -Dadditionalparam=-Xdoclint:none clean package javadoc:jar source:jar verify gpg:sign deploy 4 | -------------------------------------------------------------------------------- /src/test/resources/test.yml: -------------------------------------------------------------------------------- 1 | execution: 2 | - concurrency: 100 3 | ramp-up: 5s 4 | hold-for: 30s 5 | scenario: quick-test 6 | 7 | scenarios: 8 | quick-test: 9 | requests: 10 | - http://blazedemo.com -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /.idea/ 3 | *.iml 4 | /job/ 5 | /pwd/ 6 | # Compiled class file 7 | *.class 8 | 9 | # Log file 10 | *.log 11 | 12 | # BlueJ files 13 | *.ctxt 14 | 15 | # Mobile Tools for Java (J2ME) 16 | .mtj.tmp/ 17 | 18 | # Package Files # 19 | *.jar 20 | *.war 21 | *.ear 22 | *.tar.gz 23 | *.rar 24 | 25 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 26 | hs_err_pid* 27 | /http2/datawriter 28 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/exception/ValidationException.java: -------------------------------------------------------------------------------- 1 | package com.blazemeter.api.exception; 2 | 3 | public class ValidationException extends RuntimeException { 4 | 5 | public ValidationException() { 6 | } 7 | 8 | public ValidationException(String message) { 9 | super(message); 10 | } 11 | 12 | public ValidationException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/exception/InterruptRuntimeException.java: -------------------------------------------------------------------------------- 1 | package com.blazemeter.api.exception; 2 | 3 | public class InterruptRuntimeException extends RuntimeException{ 4 | 5 | public InterruptRuntimeException() { 6 | } 7 | 8 | public InterruptRuntimeException(String message) { 9 | super(message); 10 | } 11 | 12 | public InterruptRuntimeException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - openjdk8 5 | 6 | before_install: 7 | - curl -O -L https://github.com/inventit/mqtt-websocket-java/releases/download/1.0.1/mqtt-websocket-java-1.0.1.jar 8 | - mvn install:install-file -Dfile=mqtt-websocket-java-1.0.1.jar -DgroupId=io.inventit.dev -DartifactId=mqtt-websocket-java -Dversion=1.0.1 -Dpackaging=jar 9 | 10 | install: "mvn -Dmaven.test.skip=true clean install --batch-mode" 11 | script: "mvn -Djava.awt.headless=true -Dmaven.test.redirectTestOutputToFile=true -Dcobertura.report.format=xml --fail-at-end --batch-mode cobertura:cobertura test " 12 | 13 | after_success: 14 | - bash <(curl -s https://codecov.io/bash) 15 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/http/RequestTask.java: -------------------------------------------------------------------------------- 1 | package com.blazemeter.api.http; 2 | 3 | import okhttp3.OkHttpClient; 4 | import okhttp3.Request; 5 | import okhttp3.Response; 6 | 7 | import java.util.concurrent.Callable; 8 | 9 | public class RequestTask implements Callable { 10 | 11 | private OkHttpClient httpClient; 12 | private Request request; 13 | 14 | public RequestTask(OkHttpClient httpClient, Request request) { 15 | this.httpClient = httpClient; 16 | this.request = request; 17 | } 18 | 19 | @Override 20 | public Response call() throws Exception { 21 | return httpClient.newCall(request).execute(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/exception/ValidationExceptionTest.java: -------------------------------------------------------------------------------- 1 | package com.blazemeter.api.exception; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class ValidationExceptionTest { 8 | 9 | @Test 10 | public void test() throws Exception { 11 | ValidationException exception = new ValidationException(); 12 | assertNotNull(exception); 13 | exception = new ValidationException("msg"); 14 | assertEquals("msg", exception.getMessage()); 15 | exception = new ValidationException("msg1", new RuntimeException("nested exception")); 16 | assertEquals("nested exception", exception.getCause().getMessage()); 17 | } 18 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/exception/InterruptRuntimeExceptionTest.java: -------------------------------------------------------------------------------- 1 | package com.blazemeter.api.exception; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class InterruptRuntimeExceptionTest { 8 | @Test 9 | public void test() throws Exception { 10 | InterruptRuntimeException exception = new InterruptRuntimeException(); 11 | assertNotNull(exception); 12 | exception = new InterruptRuntimeException("msg"); 13 | assertEquals("msg", exception.getMessage()); 14 | exception = new InterruptRuntimeException("msg1", new RuntimeException("nested exception")); 15 | assertEquals("nested exception", exception.getCause().getMessage()); 16 | } 17 | } -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/ciworkflow/BuildResult.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.ciworkflow; 16 | 17 | /** 18 | * Returned as a result of CiBuild 19 | */ 20 | public enum BuildResult { 21 | SUCCESS, FAILED, ERROR, ABORTED 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/logging/impl/LoggerImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * Unless required by applicable law or agreed to in writing, software 8 | * distributed under the License is distributed on an "AS IS" BASIS, 9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | * See the License for the specific language governing permissions and 11 | * limitations under the License. 12 | */ 13 | 14 | package com.blazemeter.api.logging.impl; 15 | 16 | import java.util.logging.Logger; 17 | 18 | public class LoggerImpl extends Logger { 19 | 20 | protected LoggerImpl(String name, String resourceBundleName) { 21 | super(name, resourceBundleName); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/logging/UserNotifier.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.logging; 16 | 17 | 18 | /** 19 | * User notifier interface, that used in this library in work flows for notify user about main events 20 | */ 21 | public interface UserNotifier { 22 | 23 | void notifyInfo(String info); 24 | void notifyWarning(String warn); 25 | void notifyError(String error); 26 | 27 | } 28 | -------------------------------------------------------------------------------- /settings.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | sonatype-nexus-staging 8 | NEXUS-STAGING-USERNAME 9 | NEXUS-STAGING-USERNAME 10 | 11 | 12 | repo.jenkins-ci.org 13 | API-CLIENT-USERNAME 14 | API-CLIENT-PASSWORD 15 | 16 | 17 | 18 | 19 | 20 | maven-default-http-blocker 21 | external:dummy:* 22 | Pseudo repository to mirror external repositories initially using HTTP. 23 | http://0.0.0.0/ 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/exception/UnexpectedResponseException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.exception; 16 | 17 | public class UnexpectedResponseException extends RuntimeException { 18 | 19 | public UnexpectedResponseException() { 20 | } 21 | 22 | public UnexpectedResponseException(String message) { 23 | super(message); 24 | } 25 | 26 | public UnexpectedResponseException(String message, Throwable cause) { 27 | super(message, cause); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/logging/Logger.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.logging; 16 | 17 | /** 18 | * Logging interface, that used in this library for log events, requests and responses 19 | */ 20 | public interface Logger { 21 | 22 | void debug(String message); 23 | void debug(String message, Throwable throwable); 24 | 25 | void info(String message); 26 | void info(String message, Throwable throwable); 27 | 28 | void warn(String message); 29 | void warn(String message, Throwable throwable); 30 | 31 | void error(String message); 32 | void error(String message, Throwable throwable); 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/http/HttpLoggerTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.http; 16 | 17 | import com.blazemeter.api.logging.LoggerTest; 18 | import org.junit.Test; 19 | 20 | import static org.junit.Assert.*; 21 | 22 | public class HttpLoggerTest { 23 | 24 | @Test 25 | public void testFormat() throws Exception { 26 | LoggerTest logger = new LoggerTest(); 27 | HttpLogger httpLogger = new HttpLogger(logger); 28 | httpLogger.log("Accept: application/json"); 29 | httpLogger.log("Authorization: xxxxxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyyyyy"); 30 | assertEquals("Accept: application/json\r\nAuthorization:...yyyyyyyyyy\r\n", logger.getLogs().toString()); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/exception/UnexpectedResponseExceptionTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.exception; 16 | 17 | import org.junit.Test; 18 | 19 | import static org.junit.Assert.*; 20 | 21 | public class UnexpectedResponseExceptionTest { 22 | 23 | @Test 24 | public void test() throws Exception { 25 | UnexpectedResponseException exception = new UnexpectedResponseException(); 26 | assertNotNull(exception); 27 | exception = new UnexpectedResponseException("msg"); 28 | assertEquals("msg", exception.getMessage()); 29 | exception = new UnexpectedResponseException("msg1", new RuntimeException("nested exception")); 30 | assertEquals("nested exception", exception.getCause().getMessage()); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/logging/UserNotifierTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.logging; 16 | 17 | public class UserNotifierTest implements UserNotifier { 18 | 19 | 20 | private StringBuilder logs = new StringBuilder(); 21 | 22 | public void reset() { 23 | logs = new StringBuilder(); 24 | } 25 | 26 | public StringBuilder getLogs() { 27 | return logs; 28 | } 29 | 30 | @Override 31 | public void notifyInfo(String info) { 32 | logs.append(info).append("\r\n"); 33 | } 34 | 35 | @Override 36 | public void notifyWarning(String warn) { 37 | logs.append(warn).append("\r\n"); 38 | } 39 | 40 | @Override 41 | public void notifyError(String error) { 42 | logs.append(error).append("\r\n"); 43 | } 44 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/utils/BlazeMeterUtilsSlowEmul.java: -------------------------------------------------------------------------------- 1 | package com.blazemeter.api.utils; 2 | 3 | import com.blazemeter.api.exception.InterruptRuntimeException; 4 | import com.blazemeter.api.logging.Logger; 5 | import com.blazemeter.api.logging.UserNotifier; 6 | import net.sf.json.JSONObject; 7 | import okhttp3.Request; 8 | 9 | import java.io.IOException; 10 | 11 | public class BlazeMeterUtilsSlowEmul extends BlazeMeterUtilsEmul { 12 | 13 | public long delay = 5000; 14 | public boolean isThrowsError = true; 15 | 16 | public BlazeMeterUtilsSlowEmul(String apiKeyId, String apiKeySecret, String address, String dataAddress, UserNotifier notifier, Logger logger) { 17 | super(apiKeyId, apiKeySecret, address, dataAddress, notifier, logger); 18 | } 19 | 20 | public BlazeMeterUtilsSlowEmul(String address, String dataAddress, UserNotifier notifier, Logger logger) { 21 | super(address, dataAddress, notifier, logger); 22 | } 23 | 24 | @Override 25 | public JSONObject execute(Request request) throws IOException { 26 | makeDelay(); 27 | return super.execute(request); 28 | } 29 | 30 | @Override 31 | public String executeRequest(Request request) throws IOException { 32 | makeDelay(); 33 | return super.executeRequest(request); 34 | } 35 | 36 | protected void makeDelay() { 37 | try { 38 | Thread.currentThread().sleep(delay); 39 | } catch (InterruptedException ex) { 40 | if (isThrowsError) { 41 | throw new InterruptRuntimeException("Interrupted emul", ex); 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/http/HttpLogger.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.http; 16 | 17 | import com.blazemeter.api.logging.Logger; 18 | import okhttp3.logging.HttpLoggingInterceptor; 19 | import org.apache.commons.lang.StringUtils; 20 | 21 | /** 22 | * Logger, that log requests and responses 23 | */ 24 | public class HttpLogger implements HttpLoggingInterceptor.Logger { 25 | 26 | private final Logger logger; 27 | 28 | /** 29 | * @param logger Pass here valid implementation of @link com.blazemeter.api.logging.Logger 30 | */ 31 | public HttpLogger(Logger logger) { 32 | this.logger = logger; 33 | } 34 | 35 | @Override 36 | public void log(String message) { 37 | logger.debug(format(message)); 38 | } 39 | 40 | /** 41 | * Cuts out credentials from "Authorization" header. 42 | */ 43 | protected String format(String logEntry) { 44 | int authorization = logEntry.lastIndexOf(HttpUtils.AUTHORIZATION) + 1; 45 | if (authorization > 0) { 46 | String keyToReplace = logEntry.substring(authorization + 13, logEntry.length() - 10); 47 | return StringUtils.replace(logEntry, keyToReplace, "..."); 48 | } 49 | return logEntry; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/test/ITest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.test; 16 | 17 | import com.blazemeter.api.explorer.Master; 18 | import net.sf.json.JSONArray; 19 | 20 | import java.io.File; 21 | import java.io.IOException; 22 | 23 | public interface ITest { 24 | 25 | /** 26 | * Start BlazeMeter test 27 | * @return Master of started test 28 | */ 29 | Master start() throws IOException; 30 | 31 | /** 32 | * Start BlazeMeter test 33 | * 34 | * @return Master of started test 35 | */ 36 | Master startWithProperties(String properties) throws IOException; 37 | 38 | 39 | /** 40 | * Create empty BlazeMeter report, without starting JMeter or other testing tools. 41 | * @return Master of started test 42 | */ 43 | Master startExternal() throws IOException; 44 | 45 | /** 46 | * Upload file to BlazeMeter Test 47 | */ 48 | void uploadFile(File file) throws IOException; 49 | 50 | /** 51 | * Update BlazeMeter Test 52 | */ 53 | void update(String data) throws IOException; 54 | 55 | /** 56 | * Validate BlazeMeter Test 57 | */ 58 | void validate(String data) throws IOException; 59 | 60 | /** 61 | * Get all validation for BlazeMeter Test 62 | */ 63 | JSONArray validations() throws IOException; 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/logging/impl/FileLoggerTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * Unless required by applicable law or agreed to in writing, software 8 | * distributed under the License is distributed on an "AS IS" BASIS, 9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | * See the License for the specific language governing permissions and 11 | * limitations under the License. 12 | */ 13 | 14 | 15 | package com.blazemeter.api.logging.impl; 16 | 17 | import org.apache.commons.io.FileUtils; 18 | import org.junit.Test; 19 | 20 | import java.io.File; 21 | import java.io.IOException; 22 | 23 | import static org.junit.Assert.*; 24 | 25 | public class FileLoggerTest { 26 | 27 | @Test 28 | public void testFlow() throws IOException { 29 | File logfile = File.createTempFile("logfile", ".log"); 30 | logfile.deleteOnExit(); 31 | 32 | FileLogger logger = new FileLogger(logfile.getAbsolutePath()); 33 | logger.debug("debug"); 34 | logger.debug("debug", new RuntimeException()); 35 | 36 | logger.info("info"); 37 | logger.info("info", new RuntimeException()); 38 | 39 | logger.warn("warning"); 40 | logger.warn("warning", new RuntimeException()); 41 | 42 | logger.error("error"); 43 | logger.error("error", new RuntimeException()); 44 | 45 | logger.close(); 46 | 47 | String logs = FileUtils.readFileToString(logfile); 48 | System.out.println(logs); 49 | 50 | assertEquals(2, countSubstring("debug", logs)); 51 | assertEquals(2, countSubstring("info", logs)); 52 | assertEquals(2, countSubstring("warning", logs)); 53 | assertEquals(2, countSubstring("error", logs)); 54 | assertEquals(4, countSubstring("RuntimeException", logs)); 55 | } 56 | 57 | private static int countSubstring(String subStr, String str) { 58 | return (str.length() - str.replace(subStr, "").length()) / subStr.length(); 59 | } 60 | } -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/logging/LoggerFormatter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.logging; 16 | 17 | import java.io.PrintWriter; 18 | import java.io.StringWriter; 19 | import java.util.Date; 20 | import java.util.logging.Formatter; 21 | import java.util.logging.LogRecord; 22 | 23 | public class LoggerFormatter extends Formatter { 24 | 25 | private static final String format = "%4$-7s [%1$tF %1$tT] %5$s %6$s %n"; 26 | private final Date dat = new Date(); 27 | 28 | @Override 29 | public String format(LogRecord record) { 30 | dat.setTime(record.getMillis()); 31 | String source; 32 | if (record.getSourceClassName() != null) { 33 | source = record.getSourceClassName(); 34 | if (record.getSourceMethodName() != null) { 35 | source += " " + record.getSourceMethodName(); 36 | } 37 | } else { 38 | source = record.getLoggerName(); 39 | } 40 | String message = formatMessage(record); 41 | String throwable = ""; 42 | if (record.getThrown() != null) { 43 | StringWriter sw = new StringWriter(); 44 | PrintWriter pw = new PrintWriter(sw); 45 | pw.println(); 46 | record.getThrown().printStackTrace(pw); 47 | pw.close(); 48 | throwable = sw.toString(); 49 | } 50 | return String.format(format, 51 | dat, 52 | source, 53 | record.getLoggerName(), 54 | record.getLevel().getLocalizedName(), 55 | message, 56 | throwable); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/logging/LoggerTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.logging; 16 | 17 | 18 | public class LoggerTest implements Logger { 19 | 20 | private StringBuilder logs = new StringBuilder(); 21 | 22 | public void reset() { 23 | logs = new StringBuilder(); 24 | } 25 | 26 | public StringBuilder getLogs() { 27 | return logs; 28 | } 29 | 30 | @Override 31 | public void debug(String message) { 32 | logs.append(message).append("\r\n"); 33 | } 34 | 35 | @Override 36 | public void debug(String message, Throwable throwable) { 37 | logs.append(message).append("\r\n"); 38 | logs.append(throwable.getMessage()).append("\r\n"); 39 | } 40 | 41 | @Override 42 | public void info(String message) { 43 | logs.append(message).append("\r\n"); 44 | } 45 | 46 | @Override 47 | public void info(String message, Throwable throwable) { 48 | logs.append(message).append("\r\n"); 49 | logs.append(throwable.getMessage()).append("\r\n"); 50 | } 51 | 52 | @Override 53 | public void warn(String message) { 54 | logs.append(message).append("\r\n"); 55 | } 56 | 57 | @Override 58 | public void warn(String message, Throwable throwable) { 59 | logs.append(message).append("\r\n"); 60 | logs.append(throwable.getMessage()).append("\r\n"); 61 | } 62 | 63 | @Override 64 | public void error(String message) { 65 | logs.append(message).append("\r\n"); 66 | } 67 | 68 | @Override 69 | public void error(String message, Throwable throwable) { 70 | logs.append(message).append("\r\n"); 71 | logs.append(throwable.getMessage()).append("\r\n"); 72 | } 73 | } -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | pipeline { 2 | agent{ 3 | docker{ 4 | label 'generalNodes' 5 | image 'us.gcr.io/verdant-bulwark-278/jenkins-docker-agent:master.latest' 6 | args "-u root -v /home/jenkins/tools/:/home/jenkins/tools/ -v /var/run/docker.sock:/var/run/docker.sock" 7 | } 8 | } 9 | options { 10 | buildDiscarder(logRotator(numToKeepStr: "10")) 11 | ansiColor('xterm') 12 | timestamps() 13 | disableConcurrentBuilds() 14 | } 15 | 16 | environment { 17 | NEXUS_STAGING_CRED = credentials('blazerunner_nexus_staging_creds') 18 | API_CLIENT_CRED = credentials('blazerunner_api_client_creds') 19 | GPG_PASSPHRASE = credentials('blazerunner_api_client_gpg_passphrase') 20 | } 21 | 22 | stages { 23 | stage('Build API Client') { 24 | steps { 25 | script { 26 | sh""" 27 | sed 's/NEXUS-STAGING-USERNAME/${NEXUS_STAGING_CRED_USR}/' settings.xml 28 | sed 's/NEXUS-STAGING-PASSWORD/${NEXUS_STAGING_CRED_PSW}/' settings.xml 29 | sed 's/API-CLIENT-USERNAME/${API_CLIENT_CRED_USR}/' settings.xml 30 | sed 's/API-CLIENT-PASSWORD/${API_CLIENT_CRED_PSW}/' settings.xml 31 | mkdir ~/.m2 32 | cp settings.xml ~/.m2/settings.xml 33 | """ 34 | } 35 | } 36 | } 37 | stage('Generating GPG Key') { 38 | steps { 39 | script { 40 | sh''' 41 | cat >gpgkey < 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.test; 16 | 17 | import com.blazemeter.api.explorer.Master; 18 | import com.blazemeter.api.explorer.Session; 19 | import com.blazemeter.api.explorer.base.BZAObject; 20 | import com.blazemeter.api.utils.BlazeMeterUtils; 21 | import net.sf.json.JSONArray; 22 | import net.sf.json.JSONObject; 23 | 24 | import java.io.IOException; 25 | 26 | /** 27 | * Test which is ready to be started on server. 28 | */ 29 | public abstract class AbstractTest extends BZAObject implements ITest { 30 | 31 | /** 32 | * Master, that will be created after test has been started 33 | */ 34 | protected Master master; 35 | /** 36 | * Signature, that will be created after test has been started 37 | */ 38 | protected String signature; 39 | /** 40 | * Type of test: it can be '.http', '.multi', '.multi-location', '.taurus', '.jmeter' etc. 41 | */ 42 | protected String testType; 43 | 44 | public AbstractTest(BlazeMeterUtils utils, String id, String name, String testType) { 45 | super(utils, id, name); 46 | this.testType = testType; 47 | } 48 | 49 | protected JSONObject sendStartTest(String uri) throws IOException { 50 | return sendStartTestWithBody(uri, ""); 51 | } 52 | 53 | protected JSONObject sendStartTestWithBody(String uri, String body) throws IOException { 54 | JSONObject response = utils.execute(utils.createPost(uri, body)); 55 | return response.getJSONObject("result"); 56 | } 57 | 58 | public String prepareSessionProperties(String sesssionProperties) { 59 | JSONArray props = Session.convertProperties(sesssionProperties); 60 | 61 | JSONObject plugins = new JSONObject(); 62 | plugins.put("remoteControl", props); 63 | 64 | JSONObject configuration = new JSONObject(); 65 | configuration.put("plugins", plugins); 66 | configuration.put("enableJMeterProperties", true); 67 | 68 | JSONObject data = new JSONObject(); 69 | data.put("configuration", configuration); 70 | 71 | JSONObject request = new JSONObject(); 72 | request.put("data", data); 73 | return request.toString(); 74 | } 75 | 76 | public abstract void fillFields(JSONObject result); 77 | 78 | public Master getMaster() { 79 | return master; 80 | } 81 | 82 | public String getSignature() { 83 | return signature; 84 | } 85 | 86 | public String getTestType() { 87 | return testType; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BlazeMeter Java SDK 2 | 3 | We, at BlazeMeter, aim to bring you tools for quicker, and easier development. 4 | 5 | As part of this ambition, we are proud to present our Java SDK! 6 | 7 | Read more about this library on our [wiki page](https://github.com/Blazemeter/blazemeter-api-client/wiki). 8 | 9 | [![Build Status](https://travis-ci.org/Blazemeter/blazemeter-api-client.svg?branch=master)](https://travis-ci.org/Blazemeter/blazemeter-api-client) 10 | [![codecov](https://codecov.io/gh/Blazemeter/blazemeter-api-client/branch/master/graph/badge.svg)](https://codecov.io/gh/Blazemeter/blazemeter-api-client) 11 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/e86b726f20e046a2b89fc13c86ca6f87)](https://www.codacy.com/app/dzmitrykashlach/blazemeter-api-client?utm_source=github.com&utm_medium=referral&utm_content=Blazemeter/blazemeter-api-client&utm_campaign=Badge_Grade) 12 | 13 | Supported calls: 14 | 15 | |Description |Method |Path | 16 | |:---|:---|:---| 17 | |**Master**||| 18 | |Get Sessions|GET|/api/v4/sessions?masterId={masterId}| 19 | |Stop Master|POST|/api/v4/masters/{masterId}/stop| 20 | |Terminate Master|POST|/api/v4/masters/{masterId}/terminate| 21 | |Get Master Status Code|GET |/api/v4/masters/{masterId}/status?events=false | 22 | |Get CI Status |GET |/api/v4/masters/{masterId}/ci-status | 23 | |Get Public Report|GET|/api/v4/masters/{masterId}/public-token| 24 | |Get Summary|GET |/api/v4/masters/{masterId}/reports/main/summary | 25 | |Get JUnit Report|GET|/api/v4/masters/{masterId}/reports/thresholds?format=junit| 26 | |Get Functional Report|GET|/api/v4/masters/{masterId}| 27 | |Post Notes |PATCH|/api/v4/masters/{masterId}| 28 | |**Session**|||| 29 | |Post Properties |POST|/api/v4/sessions/{sessionId}/properties?target=all| 30 | |Get JTL Report |GET|/api/v4/sessions/{sessionId}/reports/logs| 31 | |**User**|||| 32 | |Get User|GET|/api/v4/user| 33 | |Get Accounts|GET|/api/v4/accounts?limit={limit}&sort[]={sort}| 34 | |**Workspace**|||| 35 | |Get Workspace|GET|/api/v4/workspaces/{workspaceId}| 36 | |Create Project|POST|/api/v4/projects| 37 | |Get Projects|GET|/api/v4/projects?workspaceId={workspaceId}&limit={limit}&sort[]={sort}| 38 | |Get Single Tests|GET|/api/v4/tests?workspaceId={workspaceId}&limit={limit}&sort[]={sort}| 39 | |Get Multi Tests|GET|/api/v4/multi-tests?workspaceId={workspaceId}&limit={limit}&sort[]={sort}| 40 | |**Project**|||| 41 | |Create Single Test|POST|/api/v4/tests| 42 | |Get Single Tests|GET|/api/v4/tests?projectId={projectId}&limit={limit}&sort[]={sort}| 43 | |Get Multi Tests|GET|/api/v4/multi-tests?projectId={projectId}&limit={limit}&sort[]={sort}| 44 | |**Account**|||| 45 | |Create Workspace|POST|/api/v4/workspaces| 46 | |Get Workspaces |GET|/api/v4/workspaces?accountId={accountId}&enabled={enabled}&limit={limit}| 47 | |**Single Test**|||| 48 | |Get Test|GET|/api/v4/tests/{testId}| 49 | |Start |POST|/api/v4/tests/{testId}/start| 50 | |Update Test |PATCH|/api/v4/tests/{testId}| 51 | |Upload files |POST|/api/v4/tests/{testId}/files| 52 | |Validate Test |POST|/api/v4/tests/{testId}/validate| 53 | |Get Test Validations |GET|/api/v4/tests/{testId}/validations| 54 | |**Multi Test**|||| 55 | |Get Multi Test|GET|/api/v4/multi-tests/{testId}| 56 | |Start|POST|/api/v4/multi-tests/{testId}/start| 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/http/RetryInterceptor.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.http; 16 | 17 | import com.blazemeter.api.exception.InterruptRuntimeException; 18 | import com.blazemeter.api.logging.Logger; 19 | import okhttp3.Interceptor; 20 | import okhttp3.Request; 21 | import okhttp3.Response; 22 | 23 | import java.io.IOException; 24 | import java.net.SocketTimeoutException; 25 | 26 | /** 27 | * If request was not successful, retry will be taken two times more. 28 | */ 29 | public class RetryInterceptor implements Interceptor { 30 | 31 | private final Logger logger; 32 | 33 | public RetryInterceptor(Logger logger) { 34 | this.logger = logger; 35 | } 36 | 37 | @Override 38 | public Response intercept(Chain chain) throws IOException { 39 | Request request = chain.request(); 40 | String method = request.method(); 41 | int retry = 1; 42 | int maxRetries = retry + getRetriesCount(); 43 | Response response = null; 44 | do { 45 | try { 46 | response = chain.proceed(request); 47 | logger.info("Response code = " + response.code() + " -> done " + retry + " attempt"); 48 | if (respSuccess(response) ||!shouldRetry(method, retry, maxRetries - 1)) { 49 | break; 50 | } 51 | } catch (SocketTimeoutException ex) { 52 | logger.info("Server does not send response -> done " + retry + " attempt"); 53 | logger.warn("Server does not send response", ex); 54 | if (!shouldRetry(method, retry, maxRetries - 1)) { 55 | throw ex; 56 | } 57 | } 58 | 59 | 60 | try { 61 | Thread.sleep(1000 * retry); 62 | } catch (InterruptedException e) { 63 | throw new InterruptRuntimeException("Retry was interrupted on sleep at retry # " + retry); 64 | } 65 | retry++; 66 | 67 | } while (!respSuccess(response) && shouldRetry(method, retry, maxRetries)); 68 | 69 | return response; 70 | } 71 | 72 | private boolean shouldRetry(String method, int currentRetry, int maxRetries) { 73 | return "GET".equals(method) && currentRetry < maxRetries; 74 | } 75 | 76 | private boolean respSuccess(Response response) { 77 | return response != null && response.isSuccessful(); 78 | } 79 | 80 | public static int getRetriesCount() { 81 | try { 82 | return Integer.parseInt(System.getProperty("bzm.request.retries.count", "3")); 83 | } catch (NumberFormatException ex) { 84 | return 3; 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/User.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | import com.blazemeter.api.explorer.base.BZAObject; 18 | import com.blazemeter.api.logging.Logger; 19 | import com.blazemeter.api.utils.BlazeMeterUtils; 20 | import net.sf.json.JSONArray; 21 | import net.sf.json.JSONObject; 22 | 23 | import java.io.IOException; 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | 27 | /** 28 | * Describes user. User may have one or more accounts. 29 | */ 30 | public class User extends BZAObject { 31 | 32 | 33 | public User(BlazeMeterUtils utils) { 34 | super(utils, "", ""); 35 | } 36 | 37 | public User(BlazeMeterUtils utils, String id, String name) { 38 | super(utils, id, name); 39 | } 40 | 41 | /** 42 | * GET request to 'https://a.blazemeter.com/api/v4/user' 43 | * @return User for current credentials 44 | */ 45 | public static User getUser(BlazeMeterUtils utils) throws IOException { 46 | Logger logger = utils.getLogger(); 47 | logger.info("Get User"); 48 | String uri = utils.getAddress() + "/api/v4/user"; 49 | JSONObject response = utils.execute(utils.createGet(uri)); 50 | return User.fromJSON(utils, response.getJSONObject("result")); 51 | } 52 | 53 | /** 54 | * Get Account 55 | * limit = 1000, sorted by name 56 | */ 57 | public List getAccounts() throws IOException { 58 | return getAccounts("1000", "name"); 59 | } 60 | 61 | /** 62 | * Get Accounts 63 | * GET request to 'https://a.blazemeter.com/api/v4/accounts' 64 | * @param limit of tests count in returned list 65 | * @param sort sort type: 'name', 'updated' or other * @return list of Account for user token 66 | */ 67 | public List getAccounts(String limit, String sort) throws IOException { 68 | logger.info("Get list of accounts"); 69 | String uri = utils.getAddress()+ "/api/v4/accounts"; 70 | uri = addParamToUrl(uri, "sort%5B%5D", sort); // 'sort%5B%5D' == 'sort[]' 71 | uri = addParamToUrl(uri, "limit", limit); 72 | JSONObject response = utils.execute(utils.createGet(uri)); 73 | return extractAccounts(response.getJSONArray("result")); 74 | } 75 | 76 | private List extractAccounts(JSONArray result) { 77 | List accounts = new ArrayList<>(); 78 | 79 | for (Object obj : result) { 80 | accounts.add(Account.fromJSON(utils, (JSONObject) obj)); 81 | } 82 | 83 | return accounts; 84 | } 85 | 86 | public static User fromJSON(BlazeMeterUtils utils, JSONObject result) { 87 | return new User(utils, result.getString("id"), result.getString("email")); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/explorer/base/BZAObjectTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.base; 16 | 17 | import com.blazemeter.api.logging.LoggerTest; 18 | import com.blazemeter.api.logging.UserNotifier; 19 | import com.blazemeter.api.logging.UserNotifierTest; 20 | import com.blazemeter.api.utils.BlazeMeterUtils; 21 | import org.junit.Test; 22 | 23 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 24 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 25 | import static org.junit.Assert.*; 26 | 27 | public class BZAObjectTest { 28 | 29 | @Test 30 | public void test() throws Exception { 31 | BlazeMeterUtils utils = new BlazeMeterUtils("", "", new UserNotifierTest(), new LoggerTest()); 32 | BZAObject entity = new BZAObject(utils, "id", "name"); 33 | 34 | assertEquals(utils, entity.getUtils()); 35 | assertEquals("id", entity.getId()); 36 | assertEquals("name", entity.getName()); 37 | 38 | entity.setUtils(null); 39 | entity.setId("id1"); 40 | entity.setName("name1"); 41 | 42 | assertNull(entity.getUtils()); 43 | assertEquals("id1", entity.getId()); 44 | assertEquals("name1", entity.getName()); 45 | } 46 | 47 | @Test 48 | public void testEncoding() throws Exception { 49 | LoggerTest logger = new LoggerTest(); 50 | UserNotifier notifier = new UserNotifierTest(); 51 | BlazeMeterUtils utils = new BlazeMeterUtils(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 52 | 53 | BZAObject obj = new BZAObject(utils, "id", "name"); 54 | 55 | assertEquals("123", obj.encode("123")); 56 | assertEquals("123", obj.encode("123", "Wrong encoding")); 57 | assertEquals("Cannot encode 123 to 'Wrong encoding' encoding\r\n" + 58 | "Wrong encoding\r\n", logger.getLogs().toString()); 59 | } 60 | 61 | @Test 62 | public void testAddParamsToUrl() throws Exception { 63 | LoggerTest logger = new LoggerTest(); 64 | UserNotifier notifier = new UserNotifierTest(); 65 | BlazeMeterUtils utils = new BlazeMeterUtils(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 66 | BZAObject obj = new BZAObject(utils, "", ""); 67 | 68 | String url = BZM_ADDRESS; 69 | String firstParam = obj.addParamToUrl(url, "param1", "value1"); 70 | assertEquals(url + "?param1=value1", firstParam); 71 | 72 | url = firstParam; 73 | String secondParam = obj.addParamToUrl(url, "param2", Boolean.FALSE); 74 | assertEquals(url + "¶m2=false", secondParam); 75 | 76 | url = secondParam; 77 | String noChanges = obj.addParamToUrl(url, "nullParam", null); 78 | assertEquals(url, noChanges); 79 | } 80 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/utils/BlazeMeterUtilsEmul.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.utils; 16 | 17 | import com.blazemeter.api.logging.Logger; 18 | import com.blazemeter.api.logging.UserNotifier; 19 | import net.sf.json.JSONObject; 20 | import okhttp3.Request; 21 | import okio.Buffer; 22 | 23 | import java.io.IOException; 24 | import java.util.LinkedList; 25 | 26 | 27 | public class BlazeMeterUtilsEmul extends BlazeMeterUtils { 28 | 29 | // Warning! You should use https(!) protocol! 30 | public static final String BZM_ADDRESS = "http://a.blazemeter.com"; 31 | public static final String BZM_DATA_ADDRESS = "http://data.blazemeter.com"; 32 | 33 | private LinkedList responses = new LinkedList<>(); 34 | private LinkedList requests = new LinkedList<>(); 35 | private LinkedList requestsBody = new LinkedList<>(); 36 | 37 | public BlazeMeterUtilsEmul(String apiKeyId, String apiKeySecret, String address, String dataAddress, UserNotifier notifier, Logger logger) { 38 | super(apiKeyId, apiKeySecret, address, dataAddress, notifier, logger); 39 | } 40 | 41 | public BlazeMeterUtilsEmul(String address, String dataAddress, UserNotifier notifier, Logger logger) { 42 | super(address, dataAddress, notifier, logger); 43 | } 44 | 45 | public void addEmul(String response) { 46 | responses.add(response); 47 | } 48 | 49 | public void clean() { 50 | requests.clear(); 51 | } 52 | 53 | public LinkedList getRequests() { 54 | return requests; 55 | } 56 | 57 | public LinkedList getRequestsBody() { 58 | return requestsBody; 59 | } 60 | 61 | @Override 62 | public JSONObject execute(Request request) throws IOException { 63 | extractBody(request); 64 | return JSONObject.fromObject(processResponse(getResponse(request))); 65 | } 66 | 67 | @Override 68 | public String executeRequest(Request request) throws IOException { 69 | extractBody(request); 70 | return getResponse(request); 71 | } 72 | 73 | public void extractBody(Request request) throws IOException { 74 | requests.add(request.toString()); 75 | if (request.body() != null) { 76 | Buffer buffer = new Buffer(); 77 | request.body().writeTo(buffer); 78 | requestsBody.add(buffer.toString()); 79 | } 80 | } 81 | 82 | public String getResponse(Object request) throws IOException { 83 | logger.info("Simulating request: " + request); 84 | if (responses.size() > 0) { 85 | String resp = responses.remove(); 86 | logger.info("Response: " + resp); 87 | return resp; 88 | } else { 89 | throw new IOException("No responses to emulate"); 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/base/BZAObject.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.base; 16 | 17 | import com.blazemeter.api.logging.Logger; 18 | import com.blazemeter.api.utils.BlazeMeterUtils; 19 | 20 | import java.io.UnsupportedEncodingException; 21 | import java.net.URLEncoder; 22 | 23 | 24 | /** 25 | * Base entity for BlazeMeter explorer classes 26 | * Contains settings(id,name) which are common for all 27 | * server objects(single-tests, multi-tests, master, etc) 28 | */ 29 | public class BZAObject { 30 | 31 | public static final String UTF_8 = "UTF-8"; 32 | public static final String FUNCTIONAL_GUI_TEST = "functionalGui"; 33 | public static final String TEST_SUITE = "functionalTestSuite"; 34 | protected String testType; 35 | protected String id; 36 | protected String name; 37 | protected BlazeMeterUtils utils; 38 | protected Logger logger; 39 | 40 | public BZAObject(BlazeMeterUtils utils, String id, String name) { 41 | this.utils = utils; 42 | this.id = id; 43 | this.name = name; 44 | this.logger = utils.getLogger(); 45 | } 46 | 47 | public BlazeMeterUtils getUtils() { 48 | return utils; 49 | } 50 | 51 | public void setUtils(BlazeMeterUtils utils) { 52 | this.utils = utils; 53 | } 54 | 55 | public String getId() { 56 | return id; 57 | } 58 | 59 | public String getName() { 60 | return name; 61 | } 62 | 63 | public void setId(String id) { 64 | this.id = id; 65 | } 66 | 67 | public void setName(String name) { 68 | this.name = name; 69 | } 70 | 71 | public String encode(String text) { 72 | return encode(text, UTF_8); 73 | } 74 | 75 | public String encode(String text, String encoding) { 76 | return encode(logger, text, encoding); 77 | } 78 | 79 | public static String encode(Logger logger, String text) { 80 | return encode(logger, text, UTF_8); 81 | } 82 | 83 | public static String encode(Logger logger, String text, String encoding) { 84 | try { 85 | return URLEncoder.encode(text, encoding); 86 | } catch (UnsupportedEncodingException e) { 87 | logger.warn("Cannot encode " + text + " to '" + encoding + "' encoding", e); 88 | return text; 89 | } 90 | } 91 | 92 | protected String addParamToUrl(String url, String paramName, Object paramValue) { 93 | if (paramValue == null) { 94 | return url; 95 | } else { 96 | return url.contains("?") ? 97 | (url + '&' + paramName + '=' + paramValue) : 98 | (url + '?' + paramName + '=' + paramValue); 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/Account.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | import com.blazemeter.api.explorer.base.BZAObject; 18 | import com.blazemeter.api.utils.BlazeMeterUtils; 19 | import net.sf.json.JSONArray; 20 | import net.sf.json.JSONObject; 21 | 22 | import java.io.IOException; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | /** 27 | * Corresponds to user's account on server. 28 | * Each credential can have several accounts. 29 | */ 30 | public class Account extends BZAObject { 31 | 32 | public Account(BlazeMeterUtils utils, String id, String name) { 33 | super(utils, id, name); 34 | } 35 | 36 | /** 37 | * Create Workspace in current Account 38 | * POST request to 'https://a.blazemeter.com/api/v4/workspaces' 39 | * 40 | * @param name - Name of the new Workspace 41 | */ 42 | public Workspace createWorkspace(String name) throws IOException { 43 | logger.info("Create workspace with name=" + name); 44 | String uri = utils.getAddress() + "/api/v4/workspaces"; 45 | JSONObject data = new JSONObject(); 46 | data.put("name", name); 47 | data.put("accountId", Long.parseLong(getId())); 48 | JSONObject response = utils.execute(utils.createPost(uri, data.toString())); 49 | return Workspace.fromJSON(utils, response.getJSONObject("result")); 50 | } 51 | 52 | /** 53 | * Get enabled Workspaces for current Account 54 | * limit = 1000 55 | */ 56 | public List getWorkspaces() throws IOException { 57 | return getWorkspaces(true, "1000"); 58 | } 59 | 60 | /** 61 | * Get Workspaces for current Account 62 | * GET request to 'https://a.blazemeter.com/api/v4/workspaces?accountId={accountId}&enabled=true&limit=100' 63 | * 64 | * @param enabled - if 'true' that will be return only enabled workspaces, 65 | * if 'false' - only disabled workspaces, 66 | * if null - return all workspaces 67 | * @param limit of workspaces count in returned list 68 | * @return list of Workspace in current Account 69 | */ 70 | public List getWorkspaces(Boolean enabled, String limit) throws IOException { 71 | logger.info("Get list of workspaces for account id=" + getId()); 72 | String uri = utils.getAddress() + String.format("/api/v4/workspaces?accountId=%s", encode(getId())); 73 | uri = addParamToUrl(uri, "enabled", enabled); 74 | uri = addParamToUrl(uri, "limit", limit); 75 | JSONObject response = utils.execute(utils.createGet(uri)); 76 | return extractWorkspaces(response.getJSONArray("result")); 77 | } 78 | 79 | private List extractWorkspaces(JSONArray result) { 80 | List workspaces = new ArrayList<>(); 81 | 82 | for (Object obj : result) { 83 | workspaces.add(Workspace.fromJSON(utils, (JSONObject) obj)); 84 | } 85 | 86 | return workspaces; 87 | } 88 | 89 | public static Account fromJSON(BlazeMeterUtils utils, JSONObject obj) { 90 | return new Account(utils, obj.getString("id"), obj.getString("name")); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/test/AnonymousTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.test; 16 | 17 | import com.blazemeter.api.explorer.Master; 18 | import com.blazemeter.api.explorer.Session; 19 | import com.blazemeter.api.utils.BlazeMeterUtils; 20 | import net.sf.json.JSONArray; 21 | import net.sf.json.JSONObject; 22 | 23 | import java.io.File; 24 | import java.io.IOException; 25 | 26 | /** 27 | * Test that doesn't exist on server. 28 | * Used in BZM Jmeter plugins 29 | */ 30 | public class AnonymousTest extends AbstractTest { 31 | 32 | private Session session; 33 | 34 | public AnonymousTest(BlazeMeterUtils utils) { 35 | super(utils, "", "", "external"); 36 | } 37 | 38 | @Override 39 | public Master start() throws IOException { 40 | logger.error("Start is not supported for anonymous test type"); 41 | throw new UnsupportedOperationException("Start is not supported for anonymous test type"); 42 | } 43 | 44 | @Override 45 | public Master startWithProperties(String properties) throws IOException { 46 | logger.error("Start is not supported for anonymous test type"); 47 | throw new UnsupportedOperationException("Start is not supported for anonymous test type"); 48 | } 49 | 50 | /** 51 | * GET request to 'https://a.blazemeter.com/api/v4/sessions' 52 | */ 53 | @Override 54 | public Master startExternal() throws IOException { 55 | logger.info("Start external anonymous test"); 56 | JSONObject result = sendStartTest(utils.getAddress() + "/api/v4/sessions"); 57 | fillFields(result); 58 | return master; 59 | } 60 | 61 | @Override 62 | public void fillFields(JSONObject result) { 63 | this.signature = result.getString("signature"); 64 | this.master = Master.fromJSON(utils, result.getJSONObject("master")); 65 | JSONObject test = result.getJSONObject("test"); 66 | this.id = test.getString("id"); 67 | this.name = test.getString("name"); 68 | this.session = Session.fromJSON(utils, getId(), signature, result.getJSONObject("session")); 69 | } 70 | 71 | @Override 72 | public void uploadFile(File file) throws IOException { 73 | logger.error("Upload file is not supported for anonymous test type"); 74 | throw new UnsupportedOperationException("Upload file is not supported for anonymous test type"); 75 | } 76 | 77 | @Override 78 | public void update(String data) throws IOException { 79 | logger.error("Update is not supported for anonymous test type"); 80 | throw new UnsupportedOperationException("Update is not supported for anonymous test type"); 81 | } 82 | 83 | @Override 84 | public void validate(String data) throws IOException { 85 | logger.error("Validate is not supported for anonymous test type"); 86 | throw new UnsupportedOperationException("Validate is not supported for anonymous test type"); 87 | } 88 | 89 | @Override 90 | public JSONArray validations() throws IOException { 91 | logger.error("Validations is not supported for anonymous test type"); 92 | throw new UnsupportedOperationException("Validations is not supported for anonymous test type"); 93 | } 94 | 95 | public Session getSession() { 96 | return session; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | 6 | org.sonatype.oss 7 | oss-parent 8 | 9 9 | 10 | 11 | 12 | com.blazemeter 13 | blazemeter-api-client 14 | 1.24-SNAPSHOT 15 | 16 | BlazeMeter API Client 17 | BlazeMeter API Client 18 | 19 | 20 | 21 | sat_blazemeter 22 | Dnyaneshwar Nagre (BlazeMeter) 23 | sat@blazemeter.com 24 | 25 | 26 | 27 | 28 | 29 | Apache 2.0 30 | http://www.apache.org/licenses/LICENSE-2.0 31 | repo 32 | 33 | 34 | 35 | 36 | scm:git:https://github.com/Blazemeter/blazemeter-api-client.git 37 | scm:git:https://github.com/Blazemeter/blazemeter-api-client.git 38 | HEAD 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | UTF-8 47 | 1.7 48 | 1.7 49 | 50 | 51 | 52 | 53 | 54 | org.sonatype.plugins 55 | nexus-staging-maven-plugin 56 | 1.6.7 57 | true 58 | 59 | sonatype-nexus-staging 60 | https://oss.sonatype.org/ 61 | true 62 | 63 | 64 | 65 | 66 | org.apache.maven.plugins 67 | maven-javadoc-plugin 68 | 69 | -Xdoclint:none 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | commons-io 80 | commons-io 81 | 2.7 82 | 83 | 84 | net.sf.json-lib 85 | json-lib 86 | 2.4 87 | jdk15 88 | 89 | 90 | junit 91 | junit 92 | 4.13.1 93 | 94 | 95 | 96 | 97 | com.squareup.okhttp3 98 | okhttp 99 | 3.10.0 100 | 101 | 102 | com.squareup.okhttp3 103 | logging-interceptor 104 | 3.10.0 105 | 106 | 107 | org.apache.commons 108 | commons-lang3 109 | 3.4 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/explorer/UserTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | import com.blazemeter.api.logging.LoggerTest; 18 | import com.blazemeter.api.logging.UserNotifier; 19 | import com.blazemeter.api.logging.UserNotifierTest; 20 | import com.blazemeter.api.utils.BlazeMeterUtilsEmul; 21 | import net.sf.json.JSONArray; 22 | import net.sf.json.JSONObject; 23 | import org.junit.Test; 24 | 25 | import java.util.List; 26 | 27 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 28 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 29 | import static org.junit.Assert.assertEquals; 30 | import static org.junit.Assert.assertTrue; 31 | 32 | public class UserTest { 33 | 34 | @Test 35 | public void testGetUser() throws Exception { 36 | LoggerTest logger = new LoggerTest(); 37 | UserNotifier notifier = new UserNotifierTest(); 38 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 39 | 40 | emul.addEmul(generateResponseGetUser()); 41 | 42 | User user = User.getUser(emul); 43 | assertEquals("userId", user.getId()); 44 | assertEquals("user@bzm.com", user.getName()); 45 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/user, tag=null}", emul.getRequests().get(0)); 46 | String logs = logger.getLogs().toString(); 47 | assertEquals(logs, 163, logs.length()); 48 | assertTrue(logs, logs.contains("Get User")); 49 | } 50 | 51 | public static String generateResponseGetUser() { 52 | JSONObject res = new JSONObject(); 53 | res.put("id", "userId"); 54 | res.put("email", "user@bzm.com"); 55 | 56 | JSONObject response = new JSONObject(); 57 | response.put("result", res); 58 | return response.toString(); 59 | } 60 | 61 | @Test 62 | public void testGetAccounts() throws Exception { 63 | LoggerTest logger = new LoggerTest(); 64 | UserNotifier notifier = new UserNotifierTest(); 65 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 66 | 67 | emul.addEmul(generateResponseGetAccounts()); 68 | 69 | User user = new User(emul); 70 | List accounts = user.getAccounts(); 71 | assertEquals(2, accounts.size()); 72 | for (Account account : accounts) { 73 | assertEquals("accountId", account.getId()); 74 | assertEquals("accountName", account.getName()); 75 | } 76 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/accounts?sort%5B%5D=name&limit=1000, tag=null}", emul.getRequests().get(0)); 77 | String logs = logger.getLogs().toString(); 78 | assertEquals(logs, 249, logs.length()); 79 | assertTrue(logs, logs.contains("Get list of accounts")); 80 | } 81 | 82 | public static String generateResponseGetAccounts() { 83 | JSONObject acc = new JSONObject(); 84 | acc.put("id", "accountId"); 85 | acc.put("name", "accountName"); 86 | 87 | JSONArray result = new JSONArray(); 88 | result.add(acc); 89 | result.add(acc); 90 | 91 | JSONObject response = new JSONObject(); 92 | response.put("result", result); 93 | return response.toString(); 94 | } 95 | 96 | @Test 97 | public void testFromJSON() throws Exception { 98 | LoggerTest logger = new LoggerTest(); 99 | UserNotifier notifier = new UserNotifierTest(); 100 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 101 | 102 | JSONObject object = new JSONObject(); 103 | object.put("id", "userId"); 104 | object.put("email", "userEmail"); 105 | 106 | User user = User.fromJSON(emul, object); 107 | assertEquals("userId", user.getId()); 108 | assertEquals("userEmail", user.getName()); 109 | } 110 | } -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/ciworkflow/TestsListFlow.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.ciworkflow; 16 | 17 | import com.blazemeter.api.explorer.Account; 18 | import com.blazemeter.api.explorer.User; 19 | import com.blazemeter.api.explorer.Workspace; 20 | import com.blazemeter.api.explorer.test.AbstractTest; 21 | import com.blazemeter.api.explorer.test.MultiTest; 22 | import com.blazemeter.api.explorer.test.SingleTest; 23 | import com.blazemeter.api.utils.BlazeMeterUtils; 24 | 25 | import java.io.IOException; 26 | import java.util.ArrayList; 27 | import java.util.Collections; 28 | import java.util.List; 29 | 30 | /** 31 | * Convenient wrapper for getting tests available for particular credentials. 32 | */ 33 | public class TestsListFlow { 34 | 35 | private BlazeMeterUtils utils; 36 | 37 | public TestsListFlow() { 38 | } 39 | 40 | public TestsListFlow(BlazeMeterUtils utils) { 41 | this.utils = utils; 42 | } 43 | 44 | /** 45 | * @return List of all tests that available for your credentials 46 | */ 47 | public List getUsersTests() { 48 | final List result = new ArrayList<>(); 49 | try { 50 | User user = new User(utils); 51 | List accounts = user.getAccounts(); 52 | for (Account account : accounts) { 53 | result.addAll(getTestsForAccount(account)); 54 | } 55 | } catch (IOException ex) { 56 | utils.getNotifier().notifyError("Failed to get accounts. Reason is: " + ex.getMessage()); 57 | utils.getLogger().error("Failed to get accounts. Reason is: " + ex.getMessage(), ex); 58 | } 59 | return result; 60 | } 61 | 62 | protected List getTestsForAccount(Account account) { 63 | final List result = new ArrayList<>(); 64 | try { 65 | List workspaces = account.getWorkspaces(); 66 | for (Workspace workspace : workspaces) { 67 | result.addAll(getSingleTestsForWorkspace(workspace)); 68 | result.addAll(getMultiTestsForWorkspace(workspace)); 69 | } 70 | } catch (IOException e) { 71 | utils.getNotifier().notifyError("Failed to get workspaces for account id =" + account.getId() + ". Reason is: " + e.getMessage()); 72 | utils.getLogger().error("Failed to get workspaces for account id =" + account.getId() + ". Reason is: " + e.getMessage(), e); 73 | } 74 | return result; 75 | } 76 | 77 | public List getAllTestsForWorkspace(Workspace workspace) { 78 | final List result = new ArrayList<>(); 79 | result.addAll(getSingleTestsForWorkspace(workspace)); 80 | result.addAll(getMultiTestsForWorkspace(workspace)); 81 | return result; 82 | } 83 | 84 | protected List getSingleTestsForWorkspace(Workspace workspace) { 85 | try { 86 | return workspace.getSingleTests(); 87 | } catch (IOException e) { 88 | utils.getNotifier().notifyError("Failed to get single tests for workspace id =" + workspace.getId() + ". Reason is: " + e.getMessage()); 89 | utils.getLogger().error("Failed to get single tests for workspace id =" + workspace.getId() + ". Reason is: " + e.getMessage(), e); 90 | } 91 | return Collections.emptyList(); 92 | } 93 | 94 | protected List getMultiTestsForWorkspace(Workspace workspace) { 95 | try { 96 | return workspace.getMultiTests(); 97 | } catch (IOException e) { 98 | utils.getNotifier().notifyError("Failed to get multi tests for workspace id =" + workspace.getId() + ". Reason is: " + e.getMessage()); 99 | utils.getLogger().error("Failed to get multi tests for workspace id =" + workspace.getId() + ". Reason is: " + e.getMessage(), e); 100 | } 101 | return Collections.emptyList(); 102 | } 103 | 104 | public BlazeMeterUtils getUtils() { 105 | return utils; 106 | } 107 | 108 | public void setUtils(BlazeMeterUtils utils) { 109 | this.utils = utils; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/explorer/AccountTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | import com.blazemeter.api.logging.LoggerTest; 18 | import com.blazemeter.api.logging.UserNotifier; 19 | import com.blazemeter.api.logging.UserNotifierTest; 20 | import com.blazemeter.api.utils.BlazeMeterUtilsEmul; 21 | import net.sf.json.JSONArray; 22 | import net.sf.json.JSONObject; 23 | import org.junit.Test; 24 | 25 | import java.util.List; 26 | 27 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 28 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 29 | import static org.junit.Assert.assertEquals; 30 | import static org.junit.Assert.assertTrue; 31 | 32 | public class AccountTest { 33 | 34 | @Test 35 | public void testCreateWorkspace() throws Exception { 36 | LoggerTest logger = new LoggerTest(); 37 | UserNotifier notifier = new UserNotifierTest(); 38 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 39 | 40 | 41 | emul.addEmul(generateResponseCreateWorkspace()); 42 | 43 | Account account = new Account(emul, "777", "account_name"); 44 | Workspace workspace = account.createWorkspace("NEW_WORKSPACE"); 45 | 46 | assertEquals("100", workspace.getId()); 47 | assertEquals("NEW_WORKSPACE", workspace.getName()); 48 | assertEquals("Request{method=POST, url=http://a.blazemeter.com/api/v4/workspaces, tag=null}", emul.getRequests().get(0)); 49 | String logs = logger.getLogs().toString(); 50 | assertEquals(logs, 199, logs.length()); 51 | assertTrue(logs, logs.contains("Create workspace with name=NEW_WORKSPACE")); 52 | } 53 | 54 | public static String generateResponseCreateWorkspace() { 55 | JSONObject result = new JSONObject(); 56 | result.put("id", "100"); 57 | result.put("name", "NEW_WORKSPACE"); 58 | 59 | JSONObject response = new JSONObject(); 60 | response.put("result", result); 61 | return response.toString(); 62 | } 63 | 64 | @Test 65 | public void testGetWorkspaces() throws Exception { 66 | LoggerTest logger = new LoggerTest(); 67 | UserNotifier notifier = new UserNotifierTest(); 68 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 69 | 70 | emul.addEmul(generateResponseGetWorkspaces()); 71 | 72 | Account account = new Account(emul, "777", "account_name"); 73 | List workspaces = account.getWorkspaces(); 74 | 75 | assertEquals(2, workspaces.size()); 76 | for (Workspace wsp : workspaces) { 77 | assertEquals("100", wsp.getId()); 78 | assertEquals("NEW_WORKSPACE", wsp.getName()); 79 | } 80 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/workspaces?accountId=777&enabled=true&limit=1000, tag=null}", emul.getRequests().get(0)); 81 | String logs = logger.getLogs().toString(); 82 | assertEquals(logs, 275, logs.length()); 83 | assertTrue(logs, logs.contains("Get list of workspaces for account id=777")); 84 | } 85 | 86 | public static String generateResponseGetWorkspaces() { 87 | JSONObject result = new JSONObject(); 88 | result.put("id", "100"); 89 | result.put("name", "NEW_WORKSPACE"); 90 | 91 | JSONArray results = new JSONArray(); 92 | results.add(result); 93 | results.add(result); 94 | 95 | JSONObject response = new JSONObject(); 96 | response.put("result", results); 97 | return response.toString(); 98 | } 99 | 100 | @Test 101 | public void testFromJSON() throws Exception { 102 | LoggerTest logger = new LoggerTest(); 103 | UserNotifier notifier = new UserNotifierTest(); 104 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 105 | 106 | JSONObject object = new JSONObject(); 107 | object.put("id", "accountId"); 108 | object.put("name", "accountName"); 109 | 110 | Account account = Account.fromJSON(emul, object); 111 | assertEquals("accountId", account.getId()); 112 | assertEquals("accountName", account.getName()); 113 | } 114 | } -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/test/TestDetector.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.test; 16 | 17 | import com.blazemeter.api.exception.UnexpectedResponseException; 18 | import com.blazemeter.api.logging.Logger; 19 | import com.blazemeter.api.utils.BlazeMeterUtils; 20 | import org.apache.commons.lang.StringUtils; 21 | 22 | import java.io.IOException; 23 | 24 | public class TestDetector { 25 | 26 | /** 27 | * @param utils - BlazeMeterUtils that contains logging and http setup 28 | * @param test - test Id for detected 29 | * Detect test type by test id. If test not found that return null 30 | */ 31 | public static AbstractTest detectTest(BlazeMeterUtils utils, String test) throws IOException { 32 | final Logger logger = utils.getLogger(); 33 | String testType = getTestTypeSuffix(test); 34 | String testId = getTestId(test); 35 | if (!StringUtils.isBlank(testType)) { 36 | return detectTestBySuffix(utils, testId, testType); 37 | } 38 | 39 | try { 40 | logger.info("Attempt to detect Single test type with id=" + testId); 41 | return SingleTest.getSingleTest(utils, testId); 42 | } catch (UnexpectedResponseException ex) { 43 | String msg = ex.getMessage(); 44 | if (msg.toLowerCase().contains("not found")) { 45 | logger.info("Single test with id=" + testId + " not found"); 46 | return detectMultiTest(utils, testId); 47 | } else { 48 | logger.error("Fail for detect Single test type id=" + testId + ". Reason is: " + ex.getMessage(), ex); 49 | throw ex; 50 | } 51 | } 52 | } 53 | 54 | public static AbstractTest detectMultiTest(BlazeMeterUtils utils, String testId) throws IOException { 55 | final Logger logger = utils.getLogger(); 56 | try { 57 | logger.info("Attempt to detect Multi test type with id=" + testId); 58 | return MultiTest.getMultiTest(utils, testId); 59 | } catch (UnexpectedResponseException ex) { 60 | String msg = ex.getMessage(); 61 | if (msg.toLowerCase().contains("not found")) { 62 | logger.info("Multi test with id=" + testId + " not found"); 63 | return null; 64 | } else { 65 | logger.error("Fail for detect Multi test type id=" + testId + ". Reason is: " + ex.getMessage(), ex); 66 | throw ex; 67 | } 68 | } 69 | } 70 | 71 | 72 | public static AbstractTest detectTestBySuffix(BlazeMeterUtils utils, String testId, String testType) throws IOException { 73 | switch (testType) { 74 | case "http": 75 | return SingleTest.getSingleTest(utils, testId); 76 | case "followme": 77 | return SingleTest.getSingleTest(utils, testId); 78 | case "jmeter": 79 | return SingleTest.getSingleTest(utils, testId); 80 | case "multi": 81 | return MultiTest.getMultiTest(utils, testId); 82 | case "multi-location": 83 | return MultiTest.getMultiTest(utils, testId); 84 | case "taurus": 85 | return SingleTest.getSingleTest(utils, testId); 86 | case "webdriver": 87 | return SingleTest.getSingleTest(utils, testId); 88 | default: 89 | utils.getLogger().error("Test type = " + testType + " is unexpected"); 90 | throw new IOException("Test type = " + testType + " is unexpected"); 91 | } 92 | } 93 | 94 | public static String getTestTypeSuffix(String testId) { 95 | try { 96 | int dot = testId.lastIndexOf("."); 97 | if (dot < 0) { 98 | return ""; 99 | } 100 | return testId.substring(testId.lastIndexOf(".") + 1); 101 | } catch (Exception e) { 102 | return ""; 103 | } 104 | } 105 | 106 | public static String getTestId(String testId) { 107 | try { 108 | int dot = testId.lastIndexOf("."); 109 | if (dot < 0) { 110 | return testId; 111 | } 112 | return testId.substring(0, testId.lastIndexOf(".")); 113 | } catch (Exception e) { 114 | return testId; 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/utils/BlazeMeterUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.utils; 16 | 17 | import com.blazemeter.api.exception.UnexpectedResponseException; 18 | import com.blazemeter.api.http.HttpUtils; 19 | import com.blazemeter.api.logging.Logger; 20 | import com.blazemeter.api.logging.UserNotifier; 21 | import net.sf.json.JSONException; 22 | import net.sf.json.JSONObject; 23 | import okhttp3.Credentials; 24 | import okhttp3.Request; 25 | import org.apache.commons.lang.StringUtils; 26 | 27 | 28 | public class BlazeMeterUtils extends HttpUtils { 29 | 30 | private String apiKeyId; 31 | private String apiKeySecret; 32 | protected String address; 33 | protected String dataAddress; 34 | 35 | protected UserNotifier notifier; 36 | 37 | /** 38 | * @param apiKeyId - BlazeMeter Api Key Id 39 | * @param apiKeySecret - BlazeMeter Api Key Secret 40 | * @param address - BlazeMeter app address: https://a.blazemeter.com/ 41 | * @param dataAddress - BlazeMeter data address: https://data.blazemeter.com/ 42 | * @param notifier - user notifier, to show user information 43 | * @param logger - logger, for log events of http requests / response etc. 44 | */ 45 | public BlazeMeterUtils(String apiKeyId, String apiKeySecret, 46 | String address, String dataAddress, 47 | UserNotifier notifier, Logger logger) { 48 | super(logger); 49 | this.address = address; 50 | this.dataAddress = dataAddress; 51 | this.apiKeyId = apiKeyId; 52 | this.apiKeySecret = apiKeySecret; 53 | this.notifier = notifier; 54 | } 55 | 56 | 57 | public BlazeMeterUtils(String address, String dataAddress, UserNotifier notifier, Logger logger) { 58 | this("", "", address, dataAddress, notifier, logger); 59 | } 60 | 61 | protected boolean isValidCredantials(String apiKeyId, String apiKeySecret) { 62 | return !StringUtils.isBlank(apiKeyId) && !StringUtils.isBlank(apiKeySecret); 63 | } 64 | 65 | @Override 66 | protected Request.Builder addRequiredHeader(Request.Builder requestBuilder) { 67 | return isValidCredantials(apiKeyId, apiKeySecret) ? 68 | requestBuilder.addHeader(AUTHORIZATION, Credentials.basic(apiKeyId, apiKeySecret)) : 69 | requestBuilder; 70 | } 71 | 72 | @Override 73 | protected JSONObject processResponse(String response) { 74 | String error = extractErrorMessage(response); 75 | if (error != null) { 76 | logger.error("Received response with the following error: " + error); 77 | throw new UnexpectedResponseException("Received response with the following error: " + error); 78 | } 79 | return JSONObject.fromObject(response); 80 | } 81 | 82 | @Override 83 | protected String extractErrorMessage(String response) { 84 | if (response != null && !response.isEmpty()) { 85 | try { 86 | JSONObject jsonResponse = JSONObject.fromObject(response); 87 | JSONObject errorObj = jsonResponse.getJSONObject("error"); 88 | if (errorObj.containsKey("message")) { 89 | return errorObj.getString("message"); 90 | } 91 | } catch (JSONException ex) { 92 | logger.debug("Cannot parse response: " + response, ex); 93 | return "Cannot parse response: " + response; 94 | } 95 | } 96 | return null; 97 | } 98 | 99 | public UserNotifier getNotifier() { 100 | return notifier; 101 | } 102 | 103 | public String getAddress() { 104 | return address; 105 | } 106 | 107 | public String getDataAddress() { 108 | return dataAddress; 109 | } 110 | 111 | public void setApiKeyId(String apiKeyId) { 112 | this.apiKeyId = apiKeyId; 113 | } 114 | 115 | public void setApiKeySecret(String apiKeySecret) { 116 | this.apiKeySecret = apiKeySecret; 117 | } 118 | 119 | public void setAddress(String address) { 120 | this.address = address; 121 | } 122 | 123 | public void setDataAddress(String dataAddress) { 124 | this.dataAddress = dataAddress; 125 | } 126 | 127 | public static long getCheckTimeout() { 128 | try { 129 | return Long.parseLong(System.getProperty("bzm.checkTimeout", "10000")); 130 | } catch (NumberFormatException ex) { 131 | return 10000; 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/test/MultiTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.test; 16 | 17 | import com.blazemeter.api.explorer.Master; 18 | import com.blazemeter.api.explorer.Session; 19 | import com.blazemeter.api.explorer.base.BZAObject; 20 | import com.blazemeter.api.logging.Logger; 21 | import com.blazemeter.api.utils.BlazeMeterUtils; 22 | import net.sf.json.JSONArray; 23 | import net.sf.json.JSONObject; 24 | 25 | import java.io.File; 26 | import java.io.IOException; 27 | 28 | 29 | /** 30 | * Corresponds to '.multi' or '.multi-location' tests on server. 31 | */ 32 | public class MultiTest extends AbstractTest { 33 | 34 | private static String MULTI_TESTS = "/api/v4/multi-tests"; 35 | 36 | public MultiTest(BlazeMeterUtils utils, String id, String name, String testType) { 37 | super(utils, id, name, testType); 38 | } 39 | 40 | /** 41 | * POST request to 'https://a.blazemeter.com/api/v4/multi-tests/{testId}/start' 42 | */ 43 | @Override 44 | public Master start() throws IOException { 45 | logger.info("Start multi test id=" + getId()); 46 | JSONObject result = sendStartTest(utils.getAddress() + String.format(MULTI_TESTS + "/%s/start", encode(getId()))); 47 | fillFields(result); 48 | return master; 49 | } 50 | 51 | /** 52 | * POST request to 'https://a.blazemeter.com/api/v4/multi-tests/{testId}/start' 53 | */ 54 | @Override 55 | public Master startWithProperties(String properties) throws IOException { 56 | logger.info("Start multi test id=" + getId()); 57 | JSONObject result = sendStartTestWithBody(utils.getAddress() + String.format(MULTI_TESTS + "/%s/start", encode(getId())), prepareSessionProperties(properties)); 58 | fillFields(result); 59 | return master; 60 | } 61 | 62 | 63 | @Override 64 | public Master startExternal() throws IOException { 65 | logger.error("Start external is not supported for multi test type id=" + getId()); 66 | throw new UnsupportedOperationException("Start external is not supported for multi test type id=" + getId()); 67 | } 68 | 69 | @Override 70 | public void uploadFile(File file) throws IOException { 71 | logger.error("Upload file is not supported for multi test type id=" + getId()); 72 | throw new UnsupportedOperationException("Upload file is not supported for multi test type id=" + getId()); 73 | } 74 | 75 | @Override 76 | public void update(String data) throws IOException { 77 | logger.error("Update is not supported for multi test type id=" + getId()); 78 | throw new UnsupportedOperationException("Update is not supported for multi test type id=" + getId()); 79 | } 80 | 81 | @Override 82 | public void validate(String data) throws IOException { 83 | logger.error("Validate is not supported for multi test type id=" + getId()); 84 | throw new UnsupportedOperationException("Validate is not supported for multi test type id=" + getId()); 85 | } 86 | 87 | @Override 88 | public JSONArray validations() throws IOException { 89 | logger.error("Validations is not supported for multi test type id=" + getId()); 90 | throw new UnsupportedOperationException("Validations is not supported for multi test type id=" + getId()); 91 | } 92 | 93 | /** 94 | * Get multi-test 95 | * GET request to 'https://a.blazemeter.com/api/v4/multi-tests/{testId}' 96 | * 97 | * @param utils - BlazeMeterUtils that contains logging and http setup 98 | * @param id - multi-test Id 99 | * @return MultiTest entity, which contains test ID and name (test label) 100 | */ 101 | public static MultiTest getMultiTest(BlazeMeterUtils utils, String id) throws IOException { 102 | Logger logger = utils.getLogger(); 103 | logger.info("Get Multi Test id=" + id); 104 | String uri = utils.getAddress() + String.format(MULTI_TESTS + "/%s", BZAObject.encode(logger, id)); 105 | JSONObject response = utils.execute(utils.createGet(uri)); 106 | return MultiTest.fromJSON(utils, response.getJSONObject("result")); 107 | } 108 | 109 | @Override 110 | public void fillFields(JSONObject result) { 111 | this.signature = Session.UNDEFINED; 112 | this.master = Master.fromJSON(utils, result); 113 | } 114 | 115 | public static MultiTest fromJSON(BlazeMeterUtils utils, JSONObject obj) { 116 | return new MultiTest(utils, obj.getString("id"), obj.getString("name"), obj.getString("collectionType")); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/utils/BlazeMeterUtilsTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.utils; 16 | 17 | import com.blazemeter.api.exception.UnexpectedResponseException; 18 | import com.blazemeter.api.logging.LoggerTest; 19 | import com.blazemeter.api.logging.UserNotifier; 20 | import com.blazemeter.api.logging.UserNotifierTest; 21 | import net.sf.json.JSONException; 22 | import net.sf.json.JSONObject; 23 | import okhttp3.Request; 24 | import org.junit.Test; 25 | 26 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 27 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 28 | import static org.junit.Assert.assertEquals; 29 | import static org.junit.Assert.assertNotNull; 30 | import static org.junit.Assert.fail; 31 | 32 | public class BlazeMeterUtilsTest { 33 | 34 | @Test 35 | public void testProcessResponse() throws Exception { 36 | LoggerTest logger = new LoggerTest(); 37 | UserNotifier notifier = new UserNotifierTest(); 38 | BlazeMeterUtils utils = new BlazeMeterUtils(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 39 | 40 | JSONObject result = utils.processResponse("{\"result\": \"ok\"}"); 41 | assertNotNull(result); 42 | assertEquals("ok", result.get("result")); 43 | result = utils.processResponse("{\"result\": \"ok\", \"error\": null}"); 44 | assertNotNull(result); 45 | assertEquals("ok", result.get("result")); 46 | 47 | try { 48 | utils.processResponse("{\"result\": \"ok\",\"error\": {\"code\": 404, \"message\": \"Not Found: Project not found\"}}"); 49 | fail("Must fail, because response have empty 'result'"); 50 | } catch (UnexpectedResponseException ex) { 51 | assertEquals("Received response with the following error: Not Found: Project not found", ex.getMessage()); 52 | assertEquals("Received response with the following error: Not Found: Project not found\r\n", logger.getLogs().toString()); 53 | } 54 | logger.reset(); 55 | try { 56 | utils.processResponse("{\"result\": null,\"error\": {\"code\": 404, \"message\": \"Not Found: Project not found\"}}"); 57 | fail("Must fail, because response have empty 'result'"); 58 | } catch (UnexpectedResponseException ex) { 59 | assertEquals("Received response with the following error: Not Found: Project not found", ex.getMessage()); 60 | assertEquals("Received response with the following error: Not Found: Project not found\r\n", logger.getLogs().toString()); 61 | } 62 | 63 | logger.reset(); 64 | 65 | try { 66 | utils.processResponse("incorrect json"); 67 | fail("Incorrect json format"); 68 | } catch (JSONException ex) { 69 | assertEquals("A JSONObject text must begin with '{' at character 1 of incorrect json", ex.getMessage()); 70 | assertEquals("Cannot parse response: incorrect json\r\n" + 71 | "A JSONObject text must begin with '{' at character 1 of incorrect json\r\n", logger.getLogs().toString()); 72 | } catch (UnexpectedResponseException ex) { 73 | assertEquals("Received response with the following error: Cannot parse response: incorrect json", ex.getMessage()); 74 | assertEquals(194, logger.getLogs().toString().length()); 75 | } 76 | } 77 | 78 | @Test 79 | public void testSetters() throws Exception { 80 | LoggerTest logger = new LoggerTest(); 81 | UserNotifier notifier = new UserNotifierTest(); 82 | BlazeMeterUtils utils = new BlazeMeterUtils(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 83 | 84 | Request.Builder builder = new Request.Builder().url(BZM_ADDRESS).get(); 85 | 86 | Request request = utils.addRequiredHeader(builder).build(); 87 | assertEquals(0, request.headers().size()); 88 | utils.setAddress(BZM_ADDRESS); 89 | utils.setDataAddress(BZM_DATA_ADDRESS); 90 | utils.setApiKeyId("xxxx"); 91 | utils.setApiKeySecret("yyy"); 92 | request = utils.addRequiredHeader(builder).build(); 93 | assertEquals(1, request.headers().size()); 94 | assertEquals(BZM_ADDRESS, utils.getAddress()); 95 | assertEquals(BZM_DATA_ADDRESS, utils.getDataAddress()); 96 | } 97 | 98 | @Test 99 | public void testGetTimeoutFailed() throws Exception { 100 | System.setProperty("bzm.checkTimeout", "aaaa"); 101 | try { 102 | long checkTimeout = BlazeMeterUtils.getCheckTimeout(); 103 | assertEquals(10000, checkTimeout); 104 | } finally { 105 | System.setProperty("bzm.checkTimeout", "10000"); 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/Project.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | import com.blazemeter.api.explorer.base.BZAObject; 18 | import com.blazemeter.api.explorer.test.MultiTest; 19 | import com.blazemeter.api.explorer.test.SingleTest; 20 | import com.blazemeter.api.utils.BlazeMeterUtils; 21 | import net.sf.json.JSONArray; 22 | import net.sf.json.JSONObject; 23 | 24 | import java.io.IOException; 25 | import java.util.ArrayList; 26 | import java.util.List; 27 | 28 | /** 29 | * Project is set of tests. 30 | * Each project belongs to some workspace 31 | */ 32 | public class Project extends BZAObject { 33 | 34 | public static final String DEFAULT_PROJECT = "Default project"; 35 | 36 | public Project(BlazeMeterUtils utils, String id, String name) { 37 | super(utils, id, name); 38 | } 39 | 40 | /** 41 | * Create Test in current Project 42 | * POST request to 'https://a.blazemeter.com/api/v4/tests' 43 | * @param name - title of the new Test 44 | */ 45 | public SingleTest createSingleTest(String name) throws IOException { 46 | logger.info("Create single test with name=" + name); 47 | String uri = utils.getAddress() + "/api/v4/tests"; 48 | JSONObject response = utils.execute(utils.createPost(uri, generateRequestBody(name).toString())); 49 | return SingleTest.fromJSON(utils, response.getJSONObject("result")); 50 | } 51 | 52 | private JSONObject generateRequestBody(String name) { 53 | JSONObject data = new JSONObject(); 54 | data.put("projectId", Long.parseLong(getId())); 55 | JSONObject configuration = new JSONObject(); 56 | configuration.put("type", "external"); 57 | data.put("configuration", configuration); 58 | data.put("name", name); 59 | return data; 60 | } 61 | 62 | /** 63 | * Get Single tests for Project 64 | * limit = 10000, sorted by name 65 | */ 66 | public List getSingleTests() throws IOException { 67 | return getSingleTests("10000", "name"); 68 | } 69 | 70 | /** 71 | * Get Single tests for Project 72 | * GET request to 'https://a.blazemeter.com/api/v4/tests??projectId={projectId}' 73 | * 74 | * @param limit of tests count in returned list 75 | * @param sort sort type: 'name', 'updated' or other 76 | * @return list of Tests in current Project 77 | */ 78 | public List getSingleTests(String limit, String sort) throws IOException { 79 | logger.info("Get list of single tests for project id=" + getId()); 80 | String uri = utils.getAddress() + "/api/v4/tests?projectId=" + encode(getId()); 81 | uri = addParamToUrl(uri, "sort%5B%5D", sort); // 'sort%5B%5D' == 'sort[]' 82 | uri = addParamToUrl(uri, "limit", limit); 83 | JSONObject response = utils.execute(utils.createGet(uri)); 84 | return extractSingleTests(response.getJSONArray("result")); 85 | } 86 | 87 | 88 | /** 89 | * Get Multi tests for Project 90 | * limit = 10000, sorted by name 91 | */ 92 | public List getMultiTests() throws IOException { 93 | return getMultiTests("10000", "name"); 94 | } 95 | 96 | /** 97 | * Get Multi Test for Project 98 | * GET request to 'https://a.blazemeter.com/api/v4/multi-tests??projectId={projectId}' 99 | * @param limit of tests count in returned list 100 | * @param sort sort type: 'name', 'updated' or other 101 | * @return list of Multi-Tests in current Project 102 | */ 103 | public List getMultiTests(String limit, String sort) throws IOException { 104 | logger.info("Get list of multi tests for project id=" + getId()); 105 | String uri = utils.getAddress() + "/api/v4/multi-tests?projectId=" + encode(getId()); 106 | uri = addParamToUrl(uri, "limit", limit); 107 | uri = addParamToUrl(uri, "sort%5B%5D", sort); // 'sort%5B%5D' == 'sort[]' 108 | JSONObject response = utils.execute(utils.createGet(uri)); 109 | return extractMultiTests(response.getJSONArray("result")); 110 | } 111 | 112 | 113 | private List extractSingleTests(JSONArray result) { 114 | List tests = new ArrayList<>(); 115 | 116 | for (Object obj : result) { 117 | tests.add(SingleTest.fromJSON(utils, (JSONObject) obj)); 118 | } 119 | 120 | return tests; 121 | } 122 | 123 | private List extractMultiTests(JSONArray result) { 124 | List tests = new ArrayList<>(); 125 | 126 | for (Object obj : result) { 127 | tests.add(MultiTest.fromJSON(utils, (JSONObject) obj)); 128 | } 129 | 130 | return tests; 131 | } 132 | 133 | public static Project fromJSON(BlazeMeterUtils utils, JSONObject obj) { 134 | return new Project(utils, obj.getString("id"), obj.getString("name")); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/explorer/ProjectTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | import com.blazemeter.api.explorer.test.MultiTest; 18 | import com.blazemeter.api.explorer.test.SingleTest; 19 | import com.blazemeter.api.logging.LoggerTest; 20 | import com.blazemeter.api.logging.UserNotifier; 21 | import com.blazemeter.api.logging.UserNotifierTest; 22 | import com.blazemeter.api.utils.BlazeMeterUtilsEmul; 23 | import net.sf.json.JSONArray; 24 | import net.sf.json.JSONObject; 25 | import org.junit.Test; 26 | 27 | import java.util.List; 28 | 29 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 30 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 31 | import static org.junit.Assert.assertEquals; 32 | import static org.junit.Assert.assertTrue; 33 | 34 | public class ProjectTest { 35 | 36 | @Test 37 | public void testCreateSingleTest() throws Exception { 38 | LoggerTest logger = new LoggerTest(); 39 | UserNotifier notifier = new UserNotifierTest(); 40 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 41 | 42 | emul.addEmul(generateResponseCreateProject()); 43 | 44 | Project project = new Project(emul, "10", "projectName"); 45 | SingleTest test = project.createSingleTest("NEW_TEST"); 46 | 47 | assertEquals("100", test.getId()); 48 | assertEquals("NEW_TEST", test.getName()); 49 | assertEquals("http", test.getTestType()); 50 | assertEquals("Request{method=POST, url=http://a.blazemeter.com/api/v4/tests, tag=null}", emul.getRequests().get(0)); 51 | String logs = logger.getLogs().toString(); 52 | assertEquals(logs, 218, logs.length()); 53 | assertTrue(logs, logs.contains("Create single test with name=NEW_TEST")); 54 | } 55 | 56 | public static String generateResponseCreateProject() { 57 | JSONObject configuration = new JSONObject(); 58 | configuration.put("type", "http"); 59 | 60 | JSONObject result = new JSONObject(); 61 | result.put("id", "100"); 62 | result.put("name", "NEW_TEST"); 63 | result.put("configuration", configuration); 64 | 65 | JSONObject response = new JSONObject(); 66 | response.put("result", result); 67 | return response.toString(); 68 | } 69 | 70 | @Test 71 | public void testGetSingleTests() throws Exception { 72 | LoggerTest logger = new LoggerTest(); 73 | UserNotifier notifier = new UserNotifierTest(); 74 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 75 | 76 | emul.addEmul(generateResponseGetSingleTests()); 77 | 78 | Project project = new Project(emul, "10", "projectName"); 79 | List tests = project.getSingleTests(); 80 | assertEquals(2, tests.size()); 81 | for (SingleTest t : tests) { 82 | assertEquals("100", t.getId()); 83 | assertEquals("NEW_TEST", t.getName()); 84 | assertEquals("http", t.getTestType()); 85 | } 86 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/tests?projectId=10&sort%5B%5D=name&limit=10000, tag=null}", emul.getRequests().get(0)); 87 | String logs = logger.getLogs().toString(); 88 | assertEquals(logs, 328, logs.length()); 89 | assertTrue(logs, logs.contains("Get list of single tests for project id=10")); 90 | } 91 | 92 | public static String generateResponseGetSingleTests() { 93 | JSONObject configuration = new JSONObject(); 94 | configuration.put("type", "http"); 95 | 96 | JSONObject result = new JSONObject(); 97 | result.put("id", "100"); 98 | result.put("name", "NEW_TEST"); 99 | result.put("configuration", configuration); 100 | 101 | JSONArray results = new JSONArray(); 102 | results.add(result); 103 | results.add(result); 104 | 105 | JSONObject response = new JSONObject(); 106 | response.put("result", results); 107 | return response.toString(); 108 | } 109 | 110 | @Test 111 | public void testGetMultiTests() throws Exception { 112 | LoggerTest logger = new LoggerTest(); 113 | UserNotifier notifier = new UserNotifierTest(); 114 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 115 | 116 | emul.addEmul(generateResponseGetMultiTests()); 117 | 118 | Project project = new Project(emul, "10", "projectName"); 119 | List multiTests = project.getMultiTests(); 120 | assertEquals(2, multiTests.size()); 121 | for (MultiTest t : multiTests) { 122 | assertEquals("100", t.getId()); 123 | assertEquals("NEW_TEST", t.getName()); 124 | assertEquals("multi", t.getTestType()); 125 | } 126 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/multi-tests?projectId=10&limit=10000&sort%5B%5D=name, tag=null}", emul.getRequests().get(0)); 127 | String logs = logger.getLogs().toString(); 128 | assertEquals(logs, 319, logs.length()); 129 | assertTrue(logs, logs.contains("Get list of multi tests for project id=10")); 130 | } 131 | 132 | public static String generateResponseGetMultiTests() { 133 | JSONObject result = new JSONObject(); 134 | result.put("id", "100"); 135 | result.put("name", "NEW_TEST"); 136 | result.put("collectionType", "multi"); 137 | 138 | JSONArray results = new JSONArray(); 139 | results.add(result); 140 | results.add(result); 141 | 142 | JSONObject response = new JSONObject(); 143 | response.put("result", results); 144 | return response.toString(); 145 | } 146 | 147 | @Test 148 | public void testFromJSON() throws Exception { 149 | LoggerTest logger = new LoggerTest(); 150 | UserNotifier notifier = new UserNotifierTest(); 151 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 152 | 153 | JSONObject object = new JSONObject(); 154 | object.put("id", "projectId"); 155 | object.put("name", "projectName"); 156 | 157 | Project project = Project.fromJSON(emul, object); 158 | assertEquals("projectId", project.getId()); 159 | assertEquals("projectName", project.getName()); 160 | } 161 | } -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/Session.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | 18 | import com.blazemeter.api.explorer.base.BZAObject; 19 | import com.blazemeter.api.utils.BlazeMeterUtils; 20 | import net.sf.json.JSONArray; 21 | import net.sf.json.JSONObject; 22 | import okhttp3.MediaType; 23 | import okhttp3.RequestBody; 24 | import org.apache.commons.lang.StringUtils; 25 | 26 | import java.io.IOException; 27 | import java.util.Arrays; 28 | import java.util.List; 29 | 30 | /** 31 | * Each session belongs to some Master object. 32 | */ 33 | public class Session extends BZAObject { 34 | 35 | public static final String UNDEFINED = "undefined"; 36 | 37 | private final String userId; 38 | private final String testId; 39 | private final String signature; 40 | 41 | public Session(BlazeMeterUtils utils, String id, String name, String userId, String testId, String signature) { 42 | super(utils, id, name); 43 | this.userId = userId; 44 | this.testId = testId; 45 | this.signature = signature; 46 | } 47 | 48 | /** 49 | * Send test json data for the report 50 | * POST request to 'https://a.blazemeter.com/submit.php?session_id={sessionId}&signature={signature}&test_id={testId}&user_id={userId}' 51 | * 52 | * @return session in JSONObject 53 | */ 54 | public JSONObject sendData(JSONObject data) throws IOException { 55 | logger.info("Send data to session id=" + getId()); 56 | String uri = utils.getDataAddress() + 57 | String.format("/submit.php?session_id=%s&signature=%s&test_id=%s&user_id=%s", 58 | getId(), signature, testId, userId); 59 | uri += "&pq=0&target=labels_bulk&update=1"; //TODO: % self.kpi_target 60 | String dataStr = data.toString(); 61 | logger.debug("Sending active test data: " + dataStr); 62 | JSONObject response = utils.execute(utils.createPost(uri, dataStr)); 63 | return response.getJSONObject("result").getJSONObject("session"); 64 | } 65 | 66 | 67 | /** 68 | * Send properties to test session 69 | * if properties were send correctly(server's response contains the same properties) 70 | * POST request to 'https://a.blazemeter.com/api/v4/sessions/{sessionId}/properties?target=all' 71 | */ 72 | public void postProperties(String properties) throws IOException, InterruptedException { 73 | if (StringUtils.isBlank(properties)) { 74 | logger.warn("Properties are empty, won't be sent to session = " + getId()); 75 | return; 76 | } 77 | postProperties(convertProperties(properties)); 78 | } 79 | 80 | 81 | /** 82 | * Send properties to Session. 83 | * POST request to 'https://a.blazemeter.com/api/v4/sessions/{sessionId}/properties?target=all' 84 | * 85 | * @param properties - in JSONArray. For convert from String use @link com.blazemeter.api.explorer.Session#convertProperties(java.lang.String) 86 | */ 87 | void postProperties(JSONArray properties) throws IOException, InterruptedException { 88 | logger.info("Post properties to session id=" + getId()); 89 | String uri = utils.getAddress() + String.format("/api/v4/sessions/%s/properties?target=all", encode(getId())); 90 | RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), 91 | properties.toString()); 92 | utils.execute(utils.createPost(uri, body)); 93 | } 94 | 95 | 96 | /** 97 | * GET request to 'https://a.blazemeter.com/api/v4/sessions/{sessionId}/reports/logs' 98 | * 99 | * @return url for downloading jtl report 100 | */ 101 | public String getJTLReport() throws IOException { 102 | logger.info("Get JTL report for session id=" + getId()); 103 | String uri = utils.getAddress() + String.format("/api/v4/sessions/%s/reports/logs", encode(getId())); 104 | JSONObject o = utils.execute(utils.createGet(uri)); 105 | return extractDataUrl(o); 106 | } 107 | 108 | /** 109 | * Stop anonymous session 110 | * POST request to 'https://a.blazemeter.com/api/v4/sessions/{sessionId}/terminate-external' 111 | */ 112 | public void terminateExternal() throws IOException { 113 | logger.info("Terminate external session id=" + getId()); 114 | String uri = utils.getAddress() + String.format("/api/v4/sessions/%s/terminate-external", encode(getId())); 115 | JSONObject data = new JSONObject(); 116 | data.put("signature", signature); 117 | data.put("testId", testId); 118 | data.put("sessionId", getId()); 119 | utils.executeRequest(utils.createPost(uri, data.toString())); 120 | } 121 | 122 | public String getUserId() { 123 | return userId; 124 | } 125 | 126 | public String getTestId() { 127 | return testId; 128 | } 129 | 130 | public String getSignature() { 131 | return signature; 132 | } 133 | 134 | private String extractDataUrl(JSONObject o) { 135 | JSONObject result = o.getJSONObject("result"); 136 | JSONArray data = result.getJSONArray("data"); 137 | for (int i = 0; i < data.size(); i++) { 138 | String filename = data.getJSONObject(i).getString("filename"); 139 | if (filename.endsWith("zip")) { 140 | return data.getJSONObject(i).getString("dataUrl"); 141 | } 142 | } 143 | return null; 144 | } 145 | 146 | /** 147 | * Converts String of properties "v=o,b=i" to JSONArray 148 | * which can be posted to Session. 149 | */ 150 | public static JSONArray convertProperties(String properties) { 151 | JSONArray propsArray = new JSONArray(); 152 | List propList = Arrays.asList(properties.split(",")); 153 | for (String s : propList) { 154 | JSONObject prop = new JSONObject(); 155 | List pr = Arrays.asList(s.split("=")); 156 | if (pr.size() > 1) { 157 | prop.put("key", pr.get(0).trim()); 158 | prop.put("value", pr.get(1).trim()); 159 | } 160 | propsArray.add(prop); 161 | } 162 | return propsArray; 163 | } 164 | 165 | /** 166 | * Creates Session from JSON which is received from server. 167 | */ 168 | public static Session fromJSON(BlazeMeterUtils utils, JSONObject so) { 169 | return new Session(utils, so.getString("id"), so.getString("name"), 170 | so.getString("userId"), so.getString("testId"), Session.UNDEFINED); 171 | } 172 | 173 | public static Session fromJSON(BlazeMeterUtils utils, String testId, String signature, JSONObject session) { 174 | return new Session(utils, session.getString("id"), session.getString("name"), session.getString("userId"), testId, signature); 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/test/SingleTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.test; 16 | 17 | import com.blazemeter.api.explorer.Master; 18 | import com.blazemeter.api.explorer.Session; 19 | import com.blazemeter.api.explorer.base.BZAObject; 20 | import com.blazemeter.api.logging.Logger; 21 | import com.blazemeter.api.utils.BlazeMeterUtils; 22 | import net.sf.json.JSONArray; 23 | import net.sf.json.JSONObject; 24 | 25 | import java.io.File; 26 | import java.io.IOException; 27 | import java.util.Arrays; 28 | import java.util.List; 29 | 30 | /** 31 | * Corresponds to '.jmeter' or '.http' or '.followme' or '.http' or '.taurus' tests on server. 32 | */ 33 | public class SingleTest extends AbstractTest { 34 | 35 | private static String TESTS = "/api/v4/tests"; 36 | 37 | public SingleTest(BlazeMeterUtils utils, String id, String name, String testType) { 38 | super(utils, id, name, testType); 39 | } 40 | 41 | /** 42 | * POST request to 'https://a.blazemeter.com/api/v4/tests/{testId}/start' 43 | */ 44 | @Override 45 | public Master start() throws IOException { 46 | logger.info("Start single test id=" + getId()); 47 | JSONObject result = sendStartTest(utils.getAddress() + String.format(TESTS + "/%s/start", encode(getId()))); 48 | fillFields(result); 49 | return master; 50 | } 51 | 52 | 53 | /** 54 | * POST request to 'https://a.blazemeter.com/api/v4/tests/{testId}/start' 55 | */ 56 | @Override 57 | public Master startWithProperties(String properties) throws IOException { 58 | logger.info("Start single test id=" + getId()); 59 | JSONObject result = sendStartTestWithBody(utils.getAddress() + String.format(TESTS + "/%s/start", encode(getId())), prepareSessionProperties(properties)); 60 | fillFields(result); 61 | return master; 62 | } 63 | 64 | /** 65 | * POST request to 'https://a.blazemeter.com/api/v4/tests/{testId}/start-external' 66 | */ 67 | @Override 68 | public Master startExternal() throws IOException { 69 | logger.info("Start external single test id=" + getId()); 70 | JSONObject result = sendStartTest(utils.getAddress() + String.format(TESTS + "/%s/start-external", encode(getId()))); 71 | fillFields(result); 72 | return master; 73 | } 74 | 75 | @Override 76 | public void uploadFile(File file) throws IOException { 77 | logger.info("Upload file to single test id=" + getId()); 78 | String uri = utils.getAddress() + String.format(TESTS + "/%s/files", encode(getId())); 79 | JSONObject object = utils.execute(utils.createPost(uri, file)); 80 | logger.info("File uploaded with response: " + object); 81 | } 82 | 83 | @Override 84 | public void update(String data) throws IOException { 85 | logger.info(String.format("Update single test id=%s data=%s", getId(), data)); 86 | String uri = utils.getAddress() + String.format(TESTS + "/%s", encode(getId())); 87 | JSONObject object = utils.execute(utils.createPatch(uri, data)); 88 | logger.info("Single test was updated with response: " + object); 89 | } 90 | 91 | /** 92 | * Prepare JSON for PATCH BlazeMeter Test 93 | * @param filename - file name without absolute path 94 | */ 95 | public void updateTestFilename(String filename) throws IOException { 96 | logger.info(String.format("Update single test id=%s filename=%s", getId(), filename)); 97 | 98 | if ("jmeter".equals(testType)) { 99 | updateJMeterTestFilename(filename); 100 | } else if ("taurus".equals(testType) || "functionalApi".equals(testType)) { 101 | updateTaurusTestFilename(filename); 102 | } else { 103 | logger.warn(String.format("This test type '%s' does not support script configuration", testType)); 104 | } 105 | } 106 | 107 | protected void updateTaurusTestFilename(String filename) throws IOException { 108 | JSONObject configuration = new JSONObject(); 109 | configuration.put("testMode", "script"); 110 | configuration.put("filename", filename); 111 | 112 | if (filename.endsWith(".jmx")) { 113 | configuration.put("scriptType", "jmeter"); 114 | } else if (filename.endsWith(".yml") || filename.endsWith(".yaml")) { 115 | configuration.put("scriptType", "taurus"); 116 | } else { 117 | logger.warn("Unknown script type. Please, select 'Test type' in BlazeMeter web application"); 118 | } 119 | 120 | JSONObject data = new JSONObject(); 121 | data.put("configuration", configuration); 122 | update(data.toString()); 123 | } 124 | 125 | protected void updateJMeterTestFilename(String filename) throws IOException { 126 | JSONObject jmeter = new JSONObject(); 127 | jmeter.put("filename", filename); 128 | 129 | JSONObject plugins = new JSONObject(); 130 | plugins.put("jmeter", jmeter); 131 | 132 | JSONObject configuration = new JSONObject(); 133 | configuration.put("plugins", plugins); 134 | 135 | JSONObject data = new JSONObject(); 136 | data.put("configuration", configuration); 137 | update(data.toString()); 138 | } 139 | 140 | /** 141 | * Get single test 142 | * GET request to 'https://a.blazemeter.com/api/v4/tests/{testId}' 143 | * 144 | * @param utils - BlazeMeterUtils that contains logging and http setup 145 | * @param id - test Id 146 | * @return SingleTest entity, which contains test ID and name (test label) 147 | */ 148 | public static SingleTest getSingleTest(BlazeMeterUtils utils, String id) throws IOException { 149 | Logger logger = utils.getLogger(); 150 | logger.info("Get Single Test id=" + id); 151 | String uri = utils.getAddress() + String.format(TESTS + "/%s", BZAObject.encode(logger, id)); 152 | JSONObject response = utils.execute(utils.createGet(uri)); 153 | return SingleTest.fromJSON(utils, response.getJSONObject("result")); 154 | } 155 | 156 | public void validateFiles(List fileNames) throws IOException { 157 | logger.info(String.format("Validate files in single test id=%s files=%s", getId(), Arrays.toString(fileNames.toArray(new String[0])))); 158 | JSONArray files = new JSONArray(); 159 | 160 | for (String fileName : fileNames) { 161 | JSONObject obj = new JSONObject(); 162 | obj.put("fileName", fileName); 163 | files.add(obj); 164 | } 165 | 166 | JSONObject data = new JSONObject(); 167 | data.put("files", files); 168 | 169 | validate(data.toString()); 170 | } 171 | 172 | @Override 173 | public void validate(String data) throws IOException { 174 | logger.info(String.format("Validate single test id=%s data=%s", getId(), data)); 175 | String uri = utils.getAddress() + String.format(TESTS + "/%s/validate", encode(getId())); 176 | JSONObject object = utils.execute(utils.createPost(uri, data)); 177 | logger.info("Request for validate single test got response: " + object); 178 | } 179 | 180 | @Override 181 | public JSONArray validations() throws IOException { 182 | logger.info("Get validations for single test id=" + getId()); 183 | String uri = utils.getAddress() + String.format(TESTS + "/%s/validations", encode(getId())); 184 | JSONObject object = utils.execute(utils.createGet(uri)); 185 | return object.getJSONArray("result"); 186 | } 187 | 188 | @Override 189 | public void fillFields(JSONObject result) { 190 | this.signature = Session.UNDEFINED; 191 | this.master = Master.fromJSON(utils, result); 192 | } 193 | 194 | public static SingleTest fromJSON(BlazeMeterUtils utils, JSONObject obj) { 195 | return new SingleTest(utils, obj.getString("id"), obj.getString("name"), 196 | obj.getJSONObject("configuration").getString("type")); 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/explorer/Workspace.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | import com.blazemeter.api.explorer.base.BZAObject; 18 | import com.blazemeter.api.explorer.test.MultiTest; 19 | import com.blazemeter.api.explorer.test.SingleTest; 20 | import com.blazemeter.api.logging.Logger; 21 | import com.blazemeter.api.utils.BlazeMeterUtils; 22 | import net.sf.json.JSONArray; 23 | import net.sf.json.JSONObject; 24 | 25 | import java.io.IOException; 26 | import java.util.ArrayList; 27 | import java.util.List; 28 | 29 | /** 30 | * Workspace belongs to Account and has at least one Project. 31 | */ 32 | public class Workspace extends BZAObject { 33 | 34 | public Workspace(BlazeMeterUtils utils, String id, String name) { 35 | super(utils, id, name); 36 | } 37 | 38 | /** 39 | * Get workspace 40 | * GET request to 'https://a.blazemeter.com/api/v4/workspaces/{workspaceId}' 41 | * @param utils - BlazeMeterUtils that contains logging and http setup 42 | * @param id - workspaces Id 43 | * @return Workspace entity, which contains workspace ID and name (workspace label) 44 | */ 45 | public static Workspace getWorkspace(BlazeMeterUtils utils, String id) throws IOException { 46 | Logger logger = utils.getLogger(); 47 | logger.info("Get Workspace id=" + id); 48 | String uri = utils.getAddress() + String.format("/api/v4/workspaces/%s", BZAObject.encode(logger, id)); 49 | JSONObject response = utils.execute(utils.createGet(uri)); 50 | return Workspace.fromJSON(utils, response.getJSONObject("result")); 51 | } 52 | 53 | /** 54 | * Create Project in current Workspace 55 | * POST request to 'https://a.blazemeter.com/api/v4/projects' 56 | * @param name - Name of the new Project 57 | */ 58 | public Project createProject(String name) throws IOException { 59 | logger.info("Create project with name=" + name); 60 | String uri = utils.getAddress() + "/api/v4/projects"; 61 | JSONObject data = new JSONObject(); 62 | data.put("name", name); 63 | data.put("workspaceId", Long.parseLong(getId())); 64 | JSONObject response = utils.execute(utils.createPost(uri, data.toString())); 65 | return Project.fromJSON(utils, response.getJSONObject("result")); 66 | } 67 | 68 | /** 69 | * Get Project for Workspace 70 | * limit = 10000, sorted by name 71 | */ 72 | public List getProjects() throws IOException { 73 | return getProjects("10000", "name"); 74 | } 75 | 76 | /** 77 | * Get Project for Workspace 78 | * GET request to 'https://a.blazemeter.com/api/v4/projects?workspaceId={workspaceId}&limit=99999' 79 | * @param limit of tests count in returned list 80 | * @param sort sort type: 'name', 'updated' or other 81 | * @return list of Projects in current Workspace 82 | */ 83 | public List getProjects(String limit, String sort) throws IOException { 84 | logger.info("Get list of projects for workspace id=" + getId()); 85 | String uri = utils.getAddress() + String.format("/api/v4/projects?workspaceId=%s", encode(getId())); 86 | uri = addParamToUrl(uri, "sort%5B%5D", sort); // 'sort%5B%5D' == 'sort[]' 87 | uri = addParamToUrl(uri, "limit", limit); 88 | JSONObject response = utils.execute(utils.createGet(uri)); 89 | return extractProjects(response.getJSONArray("result")); 90 | } 91 | 92 | /** 93 | * Get Single tests for Workspace 94 | * limit = 10000, sorted by name 95 | */ 96 | public List getSingleTests() throws IOException { 97 | return getSingleTests("10000", "name"); 98 | } 99 | 100 | /** 101 | * Get Single tests for Workspace 102 | * GET request to 'https://a.blazemeter.com/api/v4/tests?workspaceId={workspaceId}' 103 | * @param limit of tests count in returned list 104 | * @param sort sort type: 'name', 'updated' or other 105 | * @return list of Tests in current Workspace 106 | */ 107 | public List getSingleTests(String limit, String sort) throws IOException { 108 | logger.info("Get list of single tests for workspace id=" + getId()); 109 | String uri = utils.getAddress() + "/api/v4/tests?workspaceId=" + encode(getId()); 110 | uri = addParamToUrl(uri, "sort%5B%5D", sort); // 'sort%5B%5D' == 'sort[]' 111 | uri = addParamToUrl(uri, "limit", limit); 112 | JSONObject response = utils.execute(utils.createGet(uri)); 113 | return extractSingleTests(response.getJSONArray("result")); 114 | } 115 | 116 | /** 117 | * Get Multi tests for Workspace 118 | * limit = 10000, sorted by name 119 | */ 120 | public List getMultiTests() throws IOException { 121 | return getMultiTests("10000", "name"); 122 | } 123 | 124 | /** 125 | * Get Test Suite for Workspace 126 | * limit = 10000, sorted by name 127 | */ 128 | public List getTestSuite() throws IOException { 129 | return getTestSuite("10000", "name"); 130 | } 131 | 132 | 133 | /** 134 | * Get Multi test for Workspace 135 | * GET request to 'https://a.blazemeter.com/api/v4/multi-tests?workspaceId={workspaceId}' 136 | * @param limit of tests count in returned list 137 | * @param sort sort type: 'name', 'updated' or other 138 | * @return list of Multi-Tests in current Workspace 139 | */ 140 | public List getMultiTests(String limit, String sort) throws IOException { 141 | logger.info("Get list of multi tests for workspace id=" + getId()); 142 | String uri = utils.getAddress() + "/api/v4/multi-tests?workspaceId=" + encode(getId()); 143 | uri = addParamToUrl(uri, "sort%5B%5D", sort); // 'sort%5B%5D' == 'sort[]' 144 | uri = addParamToUrl(uri, "limit", limit); 145 | JSONObject response = utils.execute(utils.createGet(uri)); 146 | return extractMultiTests(response.getJSONArray("result")); 147 | } 148 | 149 | /** 150 | * Get Test suite for Workspace 151 | * GET request to 'https://a.blazemeter.com/api/v4/multi-tests?workspaceId={workspaceId}&platform=functional' 152 | * @param limit of tests count in returned list 153 | * @param sort sort type: 'name', 'updated' or other 154 | * @return list of Test-suite in current Workspace 155 | */ 156 | public List getTestSuite(String limit, String sort) throws IOException 157 | { 158 | logger.info("Get list of test suite for workspace id=" + getId()); 159 | String uri = utils.getAddress() + "/api/v4/multi-tests?workspaceId="+encode(getId())+"&platform=functional"; 160 | uri = addParamToUrl(uri, "sort%5B%5D", sort); 161 | uri = addParamToUrl(uri, "limit", limit); 162 | JSONObject response = utils.execute(utils.createGet(uri)); 163 | return extractMultiTests(response.getJSONArray("result")); 164 | } 165 | 166 | private List extractSingleTests(JSONArray result) { 167 | List tests = new ArrayList<>(); 168 | 169 | for (Object obj : result) { 170 | tests.add(SingleTest.fromJSON(utils, (JSONObject) obj)); 171 | } 172 | 173 | return tests; 174 | } 175 | 176 | private List extractMultiTests(JSONArray result) { 177 | List tests = new ArrayList<>(); 178 | 179 | for (Object obj : result) { 180 | tests.add(MultiTest.fromJSON(utils, (JSONObject) obj)); 181 | } 182 | 183 | return tests; 184 | } 185 | 186 | private List extractProjects(JSONArray result) { 187 | List projects = new ArrayList<>(); 188 | 189 | for (Object obj : result) { 190 | projects.add(Project.fromJSON(utils, (JSONObject) obj)); 191 | } 192 | 193 | return projects; 194 | } 195 | 196 | public static Workspace fromJSON(BlazeMeterUtils utils, JSONObject obj) { 197 | return new Workspace(utils, obj.getString("id"), obj.getString("name")); 198 | } 199 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/explorer/test/AnonymousTestTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.test; 16 | 17 | import com.blazemeter.api.explorer.Master; 18 | import com.blazemeter.api.explorer.Session; 19 | import com.blazemeter.api.logging.LoggerTest; 20 | import com.blazemeter.api.logging.UserNotifier; 21 | import com.blazemeter.api.logging.UserNotifierTest; 22 | import com.blazemeter.api.utils.BlazeMeterUtilsEmul; 23 | import net.sf.json.JSONObject; 24 | import org.junit.Test; 25 | 26 | import java.io.File; 27 | import java.io.IOException; 28 | 29 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 30 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 31 | import static org.junit.Assert.assertEquals; 32 | import static org.junit.Assert.assertTrue; 33 | import static org.junit.Assert.fail; 34 | 35 | public class AnonymousTestTest { 36 | 37 | @Test 38 | public void testStart() throws Exception { 39 | LoggerTest logger = new LoggerTest(); 40 | UserNotifier notifier = new UserNotifierTest(); 41 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 42 | 43 | AnonymousTest test = new AnonymousTest(emul); 44 | try { 45 | test.start(); 46 | fail("Cannot start this test type"); 47 | } catch (UnsupportedOperationException ex) { 48 | assertEquals("Start is not supported for anonymous test type", ex.getMessage()); 49 | assertEquals("Start is not supported for anonymous test type\r\n", logger.getLogs().toString()); 50 | } 51 | } 52 | 53 | @Test 54 | public void testStartExternal() throws Exception { 55 | LoggerTest logger = new LoggerTest(); 56 | UserNotifier notifier = new UserNotifierTest(); 57 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 58 | 59 | JSONObject response = new JSONObject(); 60 | response.put("result", generateResponseStartExternalAnonymousTest()); 61 | 62 | AnonymousTest test = new AnonymousTest(emul); 63 | emul.addEmul(response.toString()); 64 | Master master = test.startExternal(); 65 | assertEquals(1, emul.getRequests().size()); 66 | assertEquals("Request{method=POST, url=http://a.blazemeter.com/api/v4/sessions, tag=null}", emul.getRequests().get(0)); 67 | checkTest(test); 68 | String logs = logger.getLogs().toString(); 69 | assertEquals(logs, 396, logs.length()); 70 | assertTrue(logs, logs.contains("Start external anonymous test")); 71 | Session session = test.getSession(); 72 | assertEquals("responseSessionId", session.getId()); 73 | assertEquals("responseMasterId", master.getId()); 74 | assertEquals("external", test.getTestType()); 75 | } 76 | 77 | @Test 78 | public void testStartWithProperties() throws Exception { 79 | LoggerTest logger = new LoggerTest(); 80 | UserNotifier notifier = new UserNotifierTest(); 81 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 82 | 83 | AnonymousTest test = new AnonymousTest(emul); 84 | try { 85 | test.startWithProperties(""); 86 | fail("Cannot start this test type"); 87 | } catch (UnsupportedOperationException ex) { 88 | assertEquals("Start is not supported for anonymous test type", ex.getMessage()); 89 | assertEquals("Start is not supported for anonymous test type\r\n", logger.getLogs().toString()); 90 | } 91 | } 92 | 93 | @Test 94 | public void testUpdate() throws Exception { 95 | LoggerTest logger = new LoggerTest(); 96 | UserNotifier notifier = new UserNotifierTest(); 97 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 98 | 99 | AnonymousTest test = new AnonymousTest(emul); 100 | try { 101 | test.update(""); 102 | fail("Cannot update this test type"); 103 | } catch (UnsupportedOperationException ex) { 104 | assertEquals("Update is not supported for anonymous test type", ex.getMessage()); 105 | assertEquals("Update is not supported for anonymous test type\r\n", logger.getLogs().toString()); 106 | } 107 | } 108 | 109 | @Test 110 | public void testUploadFile() throws Exception { 111 | LoggerTest logger = new LoggerTest(); 112 | UserNotifier notifier = new UserNotifierTest(); 113 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 114 | 115 | AnonymousTest test = new AnonymousTest(emul); 116 | try { 117 | test.uploadFile(new File(".")); 118 | fail("Cannot upload file to this test type"); 119 | } catch (UnsupportedOperationException ex) { 120 | assertEquals("Upload file is not supported for anonymous test type", ex.getMessage()); 121 | assertEquals("Upload file is not supported for anonymous test type\r\n", logger.getLogs().toString()); 122 | } 123 | } 124 | 125 | public static String generateResponseStartExternalAnonymousTest() { 126 | JSONObject testResponse = new JSONObject(); 127 | testResponse.put("id", "responseTestId"); 128 | testResponse.put("name", "responseTestName"); 129 | 130 | JSONObject masterResponse = new JSONObject(); 131 | masterResponse.put("id", "responseMasterId"); 132 | masterResponse.put("name", "responseMasterName"); 133 | 134 | JSONObject sessionResponse = new JSONObject(); 135 | sessionResponse.put("id", "responseSessionId"); 136 | sessionResponse.put("name", "responseSessionName"); 137 | sessionResponse.put("userId", "responseUserId"); 138 | 139 | JSONObject result = new JSONObject(); 140 | result.put("test", testResponse); 141 | result.put("signature", "responseSignature"); 142 | result.put("master", masterResponse); 143 | result.put("session", sessionResponse); 144 | return result.toString(); 145 | } 146 | 147 | @Test 148 | public void testValidate() throws IOException { 149 | LoggerTest logger = new LoggerTest(); 150 | UserNotifier notifier = new UserNotifierTest(); 151 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 152 | 153 | AnonymousTest test = new AnonymousTest(emul); 154 | try { 155 | test.validate("."); 156 | fail("Cannot validate this test type"); 157 | } catch (UnsupportedOperationException ex) { 158 | assertEquals("Validate is not supported for anonymous test type", ex.getMessage()); 159 | assertEquals("Validate is not supported for anonymous test type\r\n", logger.getLogs().toString()); 160 | } 161 | } 162 | 163 | @Test 164 | public void testValidations() throws IOException { 165 | LoggerTest logger = new LoggerTest(); 166 | UserNotifier notifier = new UserNotifierTest(); 167 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 168 | 169 | AnonymousTest test = new AnonymousTest(emul); 170 | try { 171 | test.validations(); 172 | fail("Cannot get validations this test type"); 173 | } catch (UnsupportedOperationException ex) { 174 | assertEquals("Validations is not supported for anonymous test type", ex.getMessage()); 175 | assertEquals("Validations is not supported for anonymous test type\r\n", logger.getLogs().toString()); 176 | } 177 | } 178 | 179 | private void checkTest(AnonymousTest test) { 180 | Master master = test.getMaster(); 181 | assertEquals("responseMasterId", master.getId()); 182 | assertEquals("responseMasterName", master.getName()); 183 | assertEquals("responseSignature", test.getSignature()); 184 | } 185 | 186 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/ciworkflow/TestsListFlowTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.ciworkflow; 16 | 17 | import com.blazemeter.api.explorer.AccountTest; 18 | import com.blazemeter.api.explorer.UserTest; 19 | import com.blazemeter.api.explorer.Workspace; 20 | import com.blazemeter.api.explorer.WorkspaceTest; 21 | import com.blazemeter.api.explorer.test.AbstractTest; 22 | import com.blazemeter.api.logging.LoggerTest; 23 | import com.blazemeter.api.logging.UserNotifierTest; 24 | import com.blazemeter.api.utils.BlazeMeterUtilsEmul; 25 | import org.junit.Test; 26 | 27 | import java.util.List; 28 | 29 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 30 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 31 | import static org.junit.Assert.assertEquals; 32 | import static org.junit.Assert.assertFalse; 33 | import static org.junit.Assert.assertTrue; 34 | 35 | 36 | public class TestsListFlowTest { 37 | 38 | @Test 39 | public void testFlow() throws Exception { 40 | LoggerTest logger = new LoggerTest(); 41 | UserNotifierTest notifier = new UserNotifierTest(); 42 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 43 | 44 | emul.addEmul(UserTest.generateResponseGetAccounts()); 45 | 46 | emul.addEmul(AccountTest.generateResponseGetWorkspaces()); 47 | emul.addEmul(WorkspaceTest.generateResponseGetSingleTests()); 48 | emul.addEmul(WorkspaceTest.generateResponseGetMultiTests()); 49 | emul.addEmul(WorkspaceTest.generateResponseGetSingleTests()); 50 | emul.addEmul(WorkspaceTest.generateResponseGetMultiTests()); 51 | 52 | emul.addEmul(AccountTest.generateResponseGetWorkspaces()); 53 | emul.addEmul(WorkspaceTest.generateResponseGetSingleTests()); 54 | emul.addEmul(WorkspaceTest.generateResponseGetMultiTests()); 55 | emul.addEmul(WorkspaceTest.generateResponseGetSingleTests()); 56 | emul.addEmul(WorkspaceTest.generateResponseGetMultiTests()); 57 | 58 | TestsListFlow flow = new TestsListFlow(emul); 59 | 60 | List usersTests = flow.getUsersTests(); 61 | assertEquals(16, usersTests.size()); 62 | assertFalse(logger.getLogs().toString().contains("Fail")); 63 | List requests = emul.getRequests(); 64 | assertEquals(11, requests.size()); 65 | 66 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/accounts?sort%5B%5D=name&limit=1000, tag=null}", requests.get(0)); 67 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/workspaces?accountId=accountId&enabled=true&limit=1000, tag=null}", requests.get(1)); 68 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(2)); 69 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/multi-tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(3)); 70 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(4)); 71 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/multi-tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(5)); 72 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/workspaces?accountId=accountId&enabled=true&limit=1000, tag=null}", requests.get(6)); 73 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(7)); 74 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/multi-tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(8)); 75 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(9)); 76 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/multi-tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(10)); 77 | } 78 | 79 | @Test 80 | public void testGetters() throws Exception { 81 | LoggerTest logger = new LoggerTest(); 82 | UserNotifierTest notifier = new UserNotifierTest(); 83 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 84 | 85 | TestsListFlow flow = new TestsListFlow(); 86 | flow.setUtils(emul); 87 | assertEquals(emul, flow.getUtils()); 88 | } 89 | 90 | @Test 91 | public void testFailGetAccount() throws Exception { 92 | LoggerTest logger = new LoggerTest(); 93 | UserNotifierTest notifier = new UserNotifierTest(); 94 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 95 | TestsListFlow flow = new TestsListFlow(emul); 96 | 97 | List usersTests = flow.getUsersTests(); 98 | assertEquals(0, usersTests.size()); 99 | assertTrue(logger.getLogs().toString().contains("Failed to get accounts. Reason is:")); 100 | assertTrue(notifier.getLogs().toString().contains("Failed to get accounts. Reason is:")); 101 | } 102 | 103 | @Test 104 | public void testFailGetWorkspaces() throws Exception { 105 | LoggerTest logger = new LoggerTest(); 106 | UserNotifierTest notifier = new UserNotifierTest(); 107 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 108 | emul.addEmul(UserTest.generateResponseGetAccounts()); 109 | 110 | TestsListFlow flow = new TestsListFlow(emul); 111 | 112 | List usersTests = flow.getUsersTests(); 113 | assertEquals(0, usersTests.size()); 114 | assertTrue(logger.getLogs().toString().contains("Failed to get workspaces for account id =")); 115 | assertTrue(notifier.getLogs().toString().contains("Failed to get workspaces for account id =")); 116 | } 117 | 118 | @Test 119 | public void testFailTests() throws Exception { 120 | LoggerTest logger = new LoggerTest(); 121 | UserNotifierTest notifier = new UserNotifierTest(); 122 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 123 | emul.addEmul(UserTest.generateResponseGetAccounts()); 124 | emul.addEmul(AccountTest.generateResponseGetWorkspaces()); 125 | 126 | TestsListFlow flow = new TestsListFlow(emul); 127 | 128 | List usersTests = flow.getUsersTests(); 129 | assertEquals(0, usersTests.size()); 130 | assertTrue(logger.getLogs().toString().contains("Failed to get single tests for workspace id =")); 131 | assertTrue(notifier.getLogs().toString().contains("Failed to get single tests for workspace id =")); 132 | assertTrue(logger.getLogs().toString().contains("Failed to get multi tests for workspace id =")); 133 | assertTrue(notifier.getLogs().toString().contains("Failed to get multi tests for workspace id =")); 134 | } 135 | 136 | @Test 137 | public void testGetAllTestsForWorkspace() throws Exception { 138 | LoggerTest logger = new LoggerTest(); 139 | UserNotifierTest notifier = new UserNotifierTest(); 140 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 141 | 142 | emul.addEmul(WorkspaceTest.generateResponseGetSingleTests()); 143 | emul.addEmul(WorkspaceTest.generateResponseGetMultiTests()); 144 | 145 | TestsListFlow flow = new TestsListFlow(emul); 146 | 147 | List usersTests = flow.getAllTestsForWorkspace(new Workspace(emul, "100", "")); 148 | assertEquals(4, usersTests.size()); 149 | assertFalse(logger.getLogs().toString().contains("Fail")); 150 | List requests = emul.getRequests(); 151 | assertEquals(2, requests.size()); 152 | 153 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(0)); 154 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/multi-tests?workspaceId=100&sort%5B%5D=name&limit=10000, tag=null}", requests.get(1)); 155 | } 156 | } -------------------------------------------------------------------------------- /src/main/java/com/blazemeter/api/http/HttpUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.http; 16 | 17 | import com.blazemeter.api.exception.InterruptRuntimeException; 18 | import com.blazemeter.api.logging.Logger; 19 | import net.sf.json.JSONObject; 20 | import okhttp3.*; 21 | import okhttp3.logging.HttpLoggingInterceptor; 22 | import org.apache.commons.lang.StringUtils; 23 | 24 | import java.io.File; 25 | import java.io.IOException; 26 | import java.net.InetSocketAddress; 27 | import java.net.Proxy; 28 | import java.util.concurrent.*; 29 | 30 | /** 31 | * Class for working with HTTP requests 32 | */ 33 | public class HttpUtils { 34 | 35 | public static final String PROXY_HOST = "http.proxyHost"; 36 | public static final String PROXY_PORT = "http.proxyPort"; 37 | public static final String PROXY_USER = "http.proxyUser"; 38 | public static final String PROXY_PASS = "http.proxyPass"; 39 | 40 | protected static final String ACCEPT = "Accept"; 41 | protected static final String APP_JSON = "application/json"; 42 | protected static final String CONTENT_TYPE = "Content-type"; 43 | protected static final String APP_JSON_UTF_8 = "application/json; charset=UTF-8"; 44 | protected static final String AUTHORIZATION = "Authorization"; 45 | protected static final MediaType JSON_CONTENT = MediaType.parse("application/json; charset=utf-8"); 46 | protected static final MediaType FILE_STREAM = MediaType.parse("application/x-www-form-urlencoded"); 47 | 48 | protected Logger logger; 49 | 50 | protected OkHttpClient httpClient; 51 | protected final ExecutorService service = Executors.newFixedThreadPool(4); 52 | 53 | public HttpUtils(Logger logger) { 54 | this.logger = logger; 55 | this.httpClient = createHTTPClient(); 56 | } 57 | 58 | /** 59 | * Create Get Request 60 | */ 61 | public Request createGet(String url) { 62 | return createRequestBuilder(url).get().build(); 63 | } 64 | 65 | /** 66 | * Create Post Request with json body 67 | */ 68 | public Request createPost(String url, RequestBody data) { 69 | return createRequestBuilder(url).post(data).build(); 70 | } 71 | 72 | /** 73 | * Create Post Request with json body 74 | */ 75 | public Request createPost(String url, String data) { 76 | return createRequestBuilder(url).post(RequestBody.create(JSON_CONTENT, data)).build(); 77 | } 78 | 79 | /** 80 | * Create Post Request with json body 81 | */ 82 | public Request createPost(String url, File data) { 83 | MultipartBody.Builder bodyBuilder = new MultipartBody.Builder(); 84 | bodyBuilder.addPart(MultipartBody.Part.createFormData("file", data.getAbsolutePath(), RequestBody.create(FILE_STREAM, data))); 85 | bodyBuilder.setType(MultipartBody.FORM); 86 | return createRequestBuilder(url).post(bodyBuilder.build()).build(); 87 | } 88 | 89 | /** 90 | * Create Patch Request 91 | */ 92 | public Request createPatch(String url, String data) { 93 | return createRequestBuilder(url).patch(RequestBody.create(JSON_CONTENT, data)).build(); 94 | } 95 | 96 | /** 97 | * Create Patch Request 98 | */ 99 | public Request createPatch(String url, RequestBody data) { 100 | return createRequestBuilder(url).patch(data).build(); 101 | } 102 | 103 | /** 104 | * Execute Http request 105 | * @param request - HTTP Request 106 | * @return - response in JSONObject 107 | */ 108 | public JSONObject execute(Request request) throws IOException { 109 | return processResponse(executeRequest(request)); 110 | } 111 | 112 | protected JSONObject processResponse(String response) { 113 | return JSONObject.fromObject(response); 114 | } 115 | 116 | /** 117 | * Execute Http request 118 | * @param request - HTTP Request 119 | * @return - response in String 120 | */ 121 | public String executeRequest(Request request) throws IOException { 122 | RequestTask task = new RequestTask(httpClient, request); 123 | Future future = service.submit(task); 124 | Response response; 125 | try { 126 | response = future.get(); 127 | } catch (InterruptedException e) { 128 | future.cancel(true); 129 | logger.warn("Caught InterruptedException ", e); 130 | throw new InterruptRuntimeException("Request has been interrupted", e); 131 | } catch (ExecutionException e) { 132 | future.cancel(true); 133 | logger.warn("Caught ExecutionException ", e); 134 | throw new IOException(e.getMessage(), e); 135 | } 136 | return response.body().string(); 137 | } 138 | 139 | protected String extractErrorMessage(String response) { 140 | return response; 141 | } 142 | 143 | protected Request.Builder addRequiredHeader(Request.Builder requestBuilder) { 144 | // NOOP 145 | return requestBuilder; 146 | } 147 | 148 | private Request.Builder createRequestBuilder(String url) { 149 | final Request.Builder builder = new Request.Builder().url(modifyRequestUrl(url)). 150 | addHeader(ACCEPT, APP_JSON). 151 | addHeader(CONTENT_TYPE, APP_JSON_UTF_8); 152 | return addRequiredHeader(builder); 153 | } 154 | 155 | /** 156 | * Override this method if you want add some require additional params to your URL 157 | */ 158 | protected String modifyRequestUrl(String url) { 159 | return url; 160 | } 161 | 162 | public Logger getLogger() { 163 | return logger; 164 | } 165 | 166 | public void setLogger(Logger logger) { 167 | this.logger = logger; 168 | } 169 | 170 | protected OkHttpClient createHTTPClient() { 171 | Proxy proxy = Proxy.NO_PROXY; 172 | Authenticator auth = Authenticator.NONE; 173 | try { 174 | String proxyHost = System.getProperty(PROXY_HOST); 175 | if (!StringUtils.isBlank(proxyHost)) { 176 | logger.info("Using http.proxyHost = " + proxyHost); 177 | int proxyPort = getProxyPort(); 178 | proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); 179 | auth = createAuthenticator(); 180 | } 181 | 182 | HttpLoggingInterceptor httpLog = new HttpLoggingInterceptor(new HttpLogger(logger)); 183 | httpLog.setLevel(HttpLoggingInterceptor.Level.BODY); 184 | 185 | return new OkHttpClient.Builder() 186 | .addInterceptor(new RetryInterceptor(logger)) 187 | .addInterceptor(httpLog) 188 | .connectTimeout(180, TimeUnit.SECONDS) 189 | .readTimeout(60, TimeUnit.SECONDS) 190 | .proxy(proxy) 191 | .proxyAuthenticator(auth).build(); 192 | } catch (Exception ex) { 193 | logger.warn("ERROR Instantiating HTTPClient. Exception received: " + ex.getMessage(), ex); 194 | throw new RuntimeException("ERROR Instantiating HTTPClient. Exception received: " + ex.getMessage(), ex); 195 | } 196 | } 197 | 198 | private int getProxyPort() { 199 | try { 200 | int proxyPort = Integer.parseInt(System.getProperty(PROXY_PORT)); 201 | logger.info("Using http.proxyPort = " + proxyPort); 202 | return proxyPort; 203 | } catch (NumberFormatException nfe) { 204 | logger.warn("Failed to read http.proxyPort: ", nfe); 205 | return 8080; 206 | } 207 | } 208 | 209 | private Authenticator createAuthenticator() { 210 | final String proxyUser = System.getProperty(PROXY_USER); 211 | logger.info("Using http.proxyUser = " + proxyUser); 212 | final String proxyPass = System.getProperty(PROXY_PASS); 213 | logger.info("Using http.proxyPass = " + StringUtils.left(proxyPass, 4)); 214 | if (!StringUtils.isBlank(proxyUser) && !StringUtils.isBlank(proxyPass)) { 215 | return new AuthenticatorExt(proxyUser, proxyPass); 216 | } 217 | return Authenticator.NONE; 218 | } 219 | 220 | protected static class AuthenticatorExt implements Authenticator { 221 | private final String proxyUser; 222 | private final String proxyPass; 223 | 224 | public AuthenticatorExt(String proxyUser, String proxyPass) { 225 | this.proxyUser = proxyUser; 226 | this.proxyPass = proxyPass; 227 | } 228 | 229 | // https://github.com/square/okhttp/wiki/Recipes#handling-authentication 230 | @Override 231 | public Request authenticate(Route route, Response response) throws IOException { 232 | String credential = Credentials.basic(proxyUser, proxyPass); 233 | if (response.request().header("Proxy-Authorization") != null) { 234 | return null; // Give up, we've already attempted to authenticate. 235 | } 236 | return response.request().newBuilder() 237 | .header("Proxy-Authorization", credential) 238 | .build(); 239 | } 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/http/RetryInterceptorTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.http; 16 | 17 | import com.blazemeter.api.http.RetryInterceptorTest.ChainImpl; 18 | import com.blazemeter.api.http.RetryInterceptorTest.ChainWithErrorImpl; 19 | import com.blazemeter.api.logging.LoggerTest; 20 | import com.blazemeter.api.utils.BlazeMeterUtilsEmul; 21 | 22 | import okhttp3.Call; 23 | import okhttp3.Connection; 24 | import okhttp3.Interceptor; 25 | import okhttp3.Interceptor.Chain; 26 | import okhttp3.Protocol; 27 | import okhttp3.Request; 28 | import okhttp3.RequestBody; 29 | import okhttp3.Response; 30 | import org.junit.Test; 31 | 32 | import java.io.IOException; 33 | import java.net.SocketTimeoutException; 34 | import java.util.concurrent.TimeUnit; 35 | 36 | import static com.blazemeter.api.http.HttpUtils.JSON_CONTENT; 37 | import static org.junit.Assert.assertEquals; 38 | import static org.junit.Assert.assertNotNull; 39 | import static org.junit.Assert.assertTrue; 40 | import static org.junit.Assert.fail; 41 | 42 | public class RetryInterceptorTest { 43 | 44 | @Test 45 | public void testFlow() throws Exception { 46 | LoggerTest logger = new LoggerTest(); 47 | RetryInterceptor retryInterceptor = new RetryInterceptor(logger); 48 | ChainImpl chain = new ChainImpl(); 49 | 50 | Response response = retryInterceptor.intercept(chain); 51 | assertEquals(200, response.code()); 52 | assertEquals("Response code = 200 -> done 1 attempt\r\n", logger.getLogs().toString()); 53 | logger.reset(); 54 | 55 | chain.code = 777; 56 | response = retryInterceptor.intercept(chain); 57 | assertEquals(777, response.code()); 58 | assertEquals("Response code = 777 -> done 1 attempt\r\n" + 59 | "Response code = 777 -> done 2 attempt\r\n" + 60 | "Response code = 777 -> done 3 attempt\r\n", logger.getLogs().toString()); 61 | } 62 | 63 | public static class ChainImpl implements Interceptor.Chain { 64 | 65 | public int code = 200; 66 | public String method = "GET"; 67 | public RequestBody body = null; 68 | 69 | @Override 70 | public Request request() { 71 | return new Request.Builder().url(BlazeMeterUtilsEmul.BZM_ADDRESS).method(method, body).build(); 72 | } 73 | 74 | @Override 75 | public Response proceed(Request request) throws IOException { 76 | Response.Builder responseBuilder = new Response.Builder(); 77 | return responseBuilder.code(code).request(request).protocol(Protocol.get("http/1.1")).build(); 78 | } 79 | 80 | @Override 81 | public Call call() { 82 | return null; 83 | } 84 | 85 | @Override 86 | public Connection connection() { 87 | return null; 88 | } 89 | 90 | @Override 91 | public int connectTimeoutMillis() { 92 | return 0; 93 | } 94 | 95 | @Override 96 | public Chain withConnectTimeout(int timeout, TimeUnit unit) { 97 | return this; 98 | } 99 | 100 | @Override 101 | public int readTimeoutMillis() { 102 | return 0; 103 | } 104 | 105 | @Override 106 | public Chain withReadTimeout(int timeout, TimeUnit unit) { 107 | return this; 108 | } 109 | 110 | @Override 111 | public int writeTimeoutMillis() { 112 | return 0; 113 | } 114 | 115 | @Override 116 | public Chain withWriteTimeout(int timeout, TimeUnit unit) { 117 | return this; 118 | } 119 | } 120 | 121 | @Test 122 | public void testInterrupt() throws Exception { 123 | final Throwable[] ex = {null}; 124 | Thread t = new Thread() { 125 | @Override 126 | public void run() { 127 | LoggerTest logger = new LoggerTest(); 128 | RetryInterceptor retryInterceptor = new RetryInterceptor(logger); 129 | ChainImpl chain = new ChainImpl(); 130 | chain.code = 500; 131 | try { 132 | retryInterceptor.intercept(chain); 133 | fail(); 134 | } catch (Throwable e) { 135 | ex[0] = e; 136 | } 137 | } 138 | }; 139 | t.start(); 140 | t.interrupt(); 141 | t.join(); 142 | assertNotNull(ex[0]); 143 | assertEquals("Retry was interrupted on sleep at retry # 1", ex[0].getMessage()); 144 | 145 | } 146 | 147 | public static class ChainWithErrorImpl implements Interceptor.Chain { 148 | public int successAttemptNumber = 5; 149 | public int code = 200; 150 | private int currentAttempt = 0; 151 | 152 | @Override 153 | public Request request() { 154 | return new Request.Builder().url(BlazeMeterUtilsEmul.BZM_ADDRESS).build(); 155 | } 156 | 157 | @Override 158 | public Response proceed(Request request) throws IOException { 159 | currentAttempt++; 160 | if (currentAttempt == successAttemptNumber) { 161 | Response.Builder responseBuilder = new Response.Builder(); 162 | return responseBuilder.code(code).request(request).protocol(Protocol.get("http/1.1")).build(); 163 | } 164 | throw new SocketTimeoutException("ooops"); 165 | } 166 | 167 | @Override 168 | public Call call() { 169 | return null; 170 | } 171 | 172 | @Override 173 | public Connection connection() { 174 | return null; 175 | } 176 | 177 | @Override 178 | public int connectTimeoutMillis() { 179 | return 0; 180 | } 181 | 182 | @Override 183 | public Chain withConnectTimeout(int timeout, TimeUnit unit) { 184 | return this; 185 | } 186 | 187 | @Override 188 | public int readTimeoutMillis() { 189 | return 0; 190 | } 191 | 192 | @Override 193 | public Chain withReadTimeout(int timeout, TimeUnit unit) { 194 | return this; 195 | } 196 | 197 | @Override 198 | public int writeTimeoutMillis() { 199 | return 0; 200 | } 201 | 202 | @Override 203 | public Chain withWriteTimeout(int timeout, TimeUnit unit) { 204 | return this; 205 | } 206 | } 207 | 208 | @Test 209 | public void testRetriesWithSocketTimeoutException() throws Exception { 210 | LoggerTest logger = new LoggerTest(); 211 | RetryInterceptor retryInterceptor = new RetryInterceptor(logger); 212 | ChainWithErrorImpl chain = new ChainWithErrorImpl(); 213 | 214 | try { 215 | retryInterceptor.intercept(chain); 216 | fail(); 217 | } catch (SocketTimeoutException ex) { 218 | assertEquals("ooops", ex.getMessage()); 219 | String logs = logger.getLogs().toString(); 220 | assertTrue(logs, logs.contains("Server does not send response -> done 1 attempt")); 221 | assertTrue(logs, logs.contains("Server does not send response -> done 2 attempt")); 222 | assertTrue(logs, logs.contains("Server does not send response -> done 3 attempt")); 223 | assertTrue(logs, logs.contains("Server does not send response")); 224 | } 225 | } 226 | 227 | @Test 228 | public void testRetriesWithSocketTimeoutException2() throws Exception { 229 | LoggerTest logger = new LoggerTest(); 230 | RetryInterceptor retryInterceptor = new RetryInterceptor(logger); 231 | ChainWithErrorImpl chain = new ChainWithErrorImpl(); 232 | chain.successAttemptNumber = 3; 233 | 234 | Response response = retryInterceptor.intercept(chain); 235 | assertEquals(200, response.code()); 236 | String logs = logger.getLogs().toString(); 237 | assertTrue(logs, logs.contains("Server does not send response -> done 1 attempt")); 238 | assertTrue(logs, logs.contains("Server does not send response -> done 2 attempt")); 239 | assertTrue(logs, logs.contains("Response code = 200 -> done 3 attempt")); 240 | } 241 | 242 | @Test 243 | public void testRetryPOSTRequest() throws Exception { 244 | LoggerTest logger = new LoggerTest(); 245 | RetryInterceptor retryInterceptor = new RetryInterceptor(logger); 246 | ChainImpl chain = new ChainImpl(); 247 | chain.method = "POST"; 248 | chain.body = RequestBody.create(JSON_CONTENT, "{}"); 249 | chain.code = 408; 250 | 251 | Response response = retryInterceptor.intercept(chain); 252 | assertEquals(408, response.code()); 253 | assertEquals("Response code = 408 -> done 1 attempt\r\n", logger.getLogs().toString()); 254 | } 255 | 256 | @Test 257 | public void testRetriesCount() { 258 | try { 259 | int retriesCount = RetryInterceptor.getRetriesCount(); 260 | assertEquals(3, retriesCount); 261 | System.setProperty("bzm.request.retries.count", "5"); 262 | retriesCount = RetryInterceptor.getRetriesCount(); 263 | assertEquals(5, retriesCount); 264 | System.setProperty("bzm.request.retries.count", "aaa"); 265 | retriesCount = RetryInterceptor.getRetriesCount(); 266 | assertEquals(3, retriesCount); 267 | } finally { 268 | System.clearProperty("bzm.request.retries.count"); 269 | } 270 | } 271 | 272 | @Test 273 | public void testRetriesCount2() throws Exception { 274 | LoggerTest logger = new LoggerTest(); 275 | RetryInterceptor retryInterceptor = new RetryInterceptor(logger); 276 | ChainImpl chain = new ChainImpl(); 277 | System.setProperty("bzm.request.retries.count", "2"); 278 | chain.code = 777; 279 | try { 280 | Response response = retryInterceptor.intercept(chain); 281 | assertEquals(777, response.code()); 282 | assertEquals("Response code = 777 -> done 1 attempt\r\n" + 283 | "Response code = 777 -> done 2 attempt\r\n", logger.getLogs().toString()); 284 | 285 | } finally { 286 | System.clearProperty("bzm.request.retries.count"); 287 | } 288 | } 289 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/explorer/test/MultiTestTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer.test; 16 | 17 | import com.blazemeter.api.explorer.Master; 18 | import com.blazemeter.api.explorer.Session; 19 | import com.blazemeter.api.logging.LoggerTest; 20 | import com.blazemeter.api.logging.UserNotifier; 21 | import com.blazemeter.api.logging.UserNotifierTest; 22 | import com.blazemeter.api.utils.BlazeMeterUtilsEmul; 23 | import net.sf.json.JSONObject; 24 | import org.junit.Test; 25 | 26 | import java.io.File; 27 | import java.io.IOException; 28 | 29 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 30 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 31 | import static org.junit.Assert.assertEquals; 32 | import static org.junit.Assert.assertTrue; 33 | import static org.junit.Assert.fail; 34 | 35 | public class MultiTestTest { 36 | 37 | @Test 38 | public void testStart() throws Exception { 39 | LoggerTest logger = new LoggerTest(); 40 | UserNotifier notifier = new UserNotifierTest(); 41 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 42 | 43 | JSONObject response = new JSONObject(); 44 | response.put("result", generateResponseStartMultiTest()); 45 | 46 | emul.addEmul(response.toString()); 47 | 48 | MultiTest test = new MultiTest(emul, "testId", "testName", "multi"); 49 | Master master = test.start(); 50 | 51 | assertEquals(1, emul.getRequests().size()); 52 | assertEquals("Request{method=POST, url=http://a.blazemeter.com/api/v4/multi-tests/testId/start, tag=null}", emul.getRequests().get(0)); 53 | checkTest(test); 54 | String logs = logger.getLogs().toString(); 55 | assertEquals(logs, 217, logs.length()); 56 | assertTrue(logs, logs.contains("Start multi test id=testId")); 57 | assertEquals("responseMasterId", master.getId()); 58 | assertEquals("multi", test.getTestType()); 59 | } 60 | 61 | @Test 62 | public void testStartWithProperties() throws Exception { 63 | LoggerTest logger = new LoggerTest(); 64 | UserNotifier notifier = new UserNotifierTest(); 65 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 66 | 67 | JSONObject response = new JSONObject(); 68 | response.put("result", generateResponseStartMultiTest()); 69 | 70 | emul.addEmul(response.toString()); 71 | 72 | MultiTest test = new MultiTest(emul, "testId", "testName", "multi") { 73 | @Override 74 | protected JSONObject sendStartTestWithBody(String uri, String body) throws IOException { 75 | assertEquals(body, "{\"data\":{\"configuration\":{\"plugins\":{\"remoteControl\":[{\"key\":\"command_property\",\"value\":\"fsdfsd\"},{\"key\":\"command_property2\",\"value\":\"fsdfsd22\"}]},\"enableJMeterProperties\":true}}}"); 76 | return super.sendStartTestWithBody(uri, body); 77 | } 78 | }; 79 | Master master = test.startWithProperties("command_property=fsdfsd,command_property2=fsdfsd22"); 80 | 81 | assertEquals(1, emul.getRequests().size()); 82 | assertEquals("Request{method=POST, url=http://a.blazemeter.com/api/v4/multi-tests/testId/start, tag=null}", emul.getRequests().get(0)); 83 | checkTest(test); 84 | String logs = logger.getLogs().toString(); 85 | assertEquals(logs, 217, logs.length()); 86 | assertTrue(logs, logs.contains("Start multi test id=testId")); 87 | assertEquals("responseMasterId", master.getId()); 88 | assertEquals("multi", test.getTestType()); 89 | assertTrue(emul.getRequestsBody().get(0).contains("size=179")); 90 | } 91 | 92 | @Test 93 | public void testStartExternal() throws Exception { 94 | LoggerTest logger = new LoggerTest(); 95 | UserNotifier notifier = new UserNotifierTest(); 96 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 97 | 98 | MultiTest test = new MultiTest(emul, "testId", "testName", "multi"); 99 | try { 100 | test.startExternal(); 101 | fail("Cannot start external this test type"); 102 | } catch (UnsupportedOperationException ex) { 103 | assertEquals("Start external is not supported for multi test type id=testId", ex.getMessage()); 104 | assertEquals("Start external is not supported for multi test type id=testId\r\n", logger.getLogs().toString()); 105 | } 106 | } 107 | 108 | @Test 109 | public void testUpdate() throws Exception { 110 | LoggerTest logger = new LoggerTest(); 111 | UserNotifier notifier = new UserNotifierTest(); 112 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 113 | 114 | MultiTest test = new MultiTest(emul, "testId", "testName", "multi"); 115 | try { 116 | test.update(""); 117 | fail("Cannot update this test type"); 118 | } catch (UnsupportedOperationException ex) { 119 | assertEquals("Update is not supported for multi test type id=testId", ex.getMessage()); 120 | assertEquals("Update is not supported for multi test type id=testId\r\n", logger.getLogs().toString()); 121 | } 122 | } 123 | 124 | @Test 125 | public void testUploadFile() throws Exception { 126 | LoggerTest logger = new LoggerTest(); 127 | UserNotifier notifier = new UserNotifierTest(); 128 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 129 | 130 | MultiTest test = new MultiTest(emul, "testId", "testName", "multi"); 131 | try { 132 | test.uploadFile(new File(".")); 133 | fail("Cannot upload file to this test type"); 134 | } catch (UnsupportedOperationException ex) { 135 | assertEquals("Upload file is not supported for multi test type id=testId", ex.getMessage()); 136 | assertEquals("Upload file is not supported for multi test type id=testId\r\n", logger.getLogs().toString()); 137 | } 138 | } 139 | 140 | @Test 141 | public void testValidate() throws IOException { 142 | LoggerTest logger = new LoggerTest(); 143 | UserNotifier notifier = new UserNotifierTest(); 144 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 145 | 146 | MultiTest test = new MultiTest(emul, "testId", "testName", "multi"); 147 | try { 148 | test.validate("."); 149 | fail("Cannot validate this test type"); 150 | } catch (UnsupportedOperationException ex) { 151 | assertEquals("Validate is not supported for multi test type id=testId", ex.getMessage()); 152 | assertEquals("Validate is not supported for multi test type id=testId\r\n", logger.getLogs().toString()); 153 | } 154 | } 155 | 156 | @Test 157 | public void testValidations() throws IOException { 158 | LoggerTest logger = new LoggerTest(); 159 | UserNotifier notifier = new UserNotifierTest(); 160 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 161 | 162 | MultiTest test = new MultiTest(emul, "testId", "testName", "multi"); 163 | try { 164 | test.validations(); 165 | fail("Cannot get validations this test type"); 166 | } catch (UnsupportedOperationException ex) { 167 | assertEquals("Validations is not supported for multi test type id=testId", ex.getMessage()); 168 | assertEquals("Validations is not supported for multi test type id=testId\r\n", logger.getLogs().toString()); 169 | } 170 | } 171 | 172 | public static String generateResponseStartMultiTest() { 173 | JSONObject masterResponse = new JSONObject(); 174 | masterResponse.put("id", "responseMasterId"); 175 | masterResponse.put("name", "responseMasterName"); 176 | return masterResponse.toString(); 177 | } 178 | 179 | 180 | private void checkTest(MultiTest test) { 181 | Master master = test.getMaster(); 182 | assertEquals("responseMasterId", master.getId()); 183 | assertEquals("responseMasterName", master.getName()); 184 | assertEquals(Session.UNDEFINED, test.getSignature()); 185 | } 186 | 187 | @Test 188 | public void testGetMultiTest() throws Exception { 189 | LoggerTest logger = new LoggerTest(); 190 | UserNotifier notifier = new UserNotifierTest(); 191 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 192 | emul.addEmul(generateResponseGetMultiTest()); 193 | 194 | MultiTest test = MultiTest.getMultiTest(emul, "testId"); 195 | assertEquals("testId", test.getId()); 196 | assertEquals("Multi_testName", test.getName()); 197 | assertEquals("multi", test.getTestType()); 198 | 199 | assertEquals(1, emul.getRequests().size()); 200 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/multi-tests/testId, tag=null}", emul.getRequests().get(0)); 201 | 202 | String logs = logger.getLogs().toString(); 203 | assertEquals(logs, 219, logs.length()); 204 | assertTrue(logs, logs.contains("Get Multi Test id=testId")); 205 | } 206 | 207 | public static String generateResponseGetMultiTest() { 208 | return generateResponseGetMultiTest("multi"); 209 | } 210 | 211 | public static String generateResponseGetMultiTest(String testType) { 212 | JSONObject result = new JSONObject(); 213 | result.put("id", "testId"); 214 | result.put("name", "Multi_testName"); 215 | result.put("collectionType", testType); 216 | 217 | JSONObject response = new JSONObject(); 218 | response.put("result", result); 219 | return response.toString(); 220 | } 221 | 222 | @Test 223 | public void testFromJSON() throws Exception { 224 | LoggerTest logger = new LoggerTest(); 225 | UserNotifier notifier = new UserNotifierTest(); 226 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 227 | 228 | JSONObject object = new JSONObject(); 229 | object.put("id", "testId"); 230 | object.put("name", "testName"); 231 | object.put("collectionType", "multi"); 232 | 233 | MultiTest test = MultiTest.fromJSON(emul, object); 234 | assertEquals("testId", test.getId()); 235 | assertEquals("testName", test.getName()); 236 | assertEquals("multi", test.getTestType()); 237 | } 238 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/explorer/WorkspaceTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | import com.blazemeter.api.explorer.test.MultiTest; 18 | import com.blazemeter.api.explorer.test.SingleTest; 19 | import com.blazemeter.api.logging.LoggerTest; 20 | import com.blazemeter.api.logging.UserNotifier; 21 | import com.blazemeter.api.logging.UserNotifierTest; 22 | import com.blazemeter.api.utils.BlazeMeterUtilsEmul; 23 | import net.sf.json.JSONArray; 24 | import net.sf.json.JSONObject; 25 | import org.junit.Test; 26 | 27 | import java.util.List; 28 | 29 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 30 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 31 | import static org.junit.Assert.assertEquals; 32 | import static org.junit.Assert.assertTrue; 33 | 34 | public class WorkspaceTest { 35 | 36 | @Test 37 | public void testCreateProject() throws Exception { 38 | LoggerTest logger = new LoggerTest(); 39 | UserNotifier notifier = new UserNotifierTest(); 40 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 41 | 42 | emul.addEmul(generateResponseCreateProject()); 43 | 44 | Workspace workspace = new Workspace(emul, "888", "workspace_name"); 45 | Project project = workspace.createProject("NEW_PROJECT"); 46 | assertEquals("999", project.getId()); 47 | assertEquals("NEW_PROJECT", project.getName()); 48 | assertEquals("Request{method=POST, url=http://a.blazemeter.com/api/v4/projects, tag=null}", emul.getRequests().get(0)); 49 | String logs = logger.getLogs().toString(); 50 | assertEquals(logs, 191, logs.length()); 51 | assertTrue(logs, logs.contains("Create project with name=NEW_PROJECT")); 52 | } 53 | 54 | public static String generateResponseCreateProject() { 55 | JSONObject result = new JSONObject(); 56 | result.put("id", "999"); 57 | result.put("name", "NEW_PROJECT"); 58 | 59 | JSONObject response = new JSONObject(); 60 | response.put("result", result); 61 | return response.toString(); 62 | } 63 | 64 | @Test 65 | public void testGetProjects() throws Exception { 66 | LoggerTest logger = new LoggerTest(); 67 | UserNotifier notifier = new UserNotifierTest(); 68 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 69 | 70 | emul.addEmul(generateResponseGetProjects()); 71 | 72 | Workspace workspace = new Workspace(emul, "888", "workspace_name"); 73 | List projects = workspace.getProjects(); 74 | assertEquals(2, projects.size()); 75 | for (Project p : projects) { 76 | assertEquals("999", p.getId()); 77 | assertEquals("NEW_PROJECT", p.getName()); 78 | } 79 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/projects?workspaceId=888&sort%5B%5D=name&limit=10000, tag=null}", emul.getRequests().get(0)); 80 | String logs = logger.getLogs().toString(); 81 | assertEquals(logs, 275, logs.length()); 82 | assertTrue(logs, logs.contains("Get list of projects for workspace id=888")); 83 | } 84 | 85 | public static String generateResponseGetProjects() { 86 | JSONObject project = new JSONObject(); 87 | project.put("id", "999"); 88 | project.put("name", "NEW_PROJECT"); 89 | 90 | JSONArray result = new JSONArray(); 91 | result.add(project); 92 | result.add(project); 93 | 94 | JSONObject response = new JSONObject(); 95 | response.put("result", result); 96 | return response.toString(); 97 | } 98 | 99 | @Test 100 | public void testGetSingleTests() throws Exception { 101 | LoggerTest logger = new LoggerTest(); 102 | UserNotifier notifier = new UserNotifierTest(); 103 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 104 | 105 | emul.addEmul(generateResponseGetSingleTests()); 106 | 107 | Workspace workspace = new Workspace(emul, "888", "workspace_name"); 108 | List tests = workspace.getSingleTests(); 109 | assertEquals(2, tests.size()); 110 | for (SingleTest t :tests) { 111 | assertEquals("999", t.getId()); 112 | assertEquals("SINGLE_TEST", t.getName()); 113 | assertEquals("http", t.getTestType()); 114 | } 115 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/tests?workspaceId=888&sort%5B%5D=name&limit=10000, tag=null}", emul.getRequests().get(0)); 116 | String logs = logger.getLogs().toString(); 117 | assertEquals(logs, 340, logs.length()); 118 | assertTrue(logs, logs.contains("Get list of single tests for workspace id=888")); 119 | } 120 | 121 | public static String generateResponseGetSingleTests() { 122 | JSONObject configuration = new JSONObject(); 123 | configuration.put("type", "http"); 124 | 125 | JSONObject test = new JSONObject(); 126 | test.put("id", "999"); 127 | test.put("name", "SINGLE_TEST"); 128 | test.put("configuration", configuration); 129 | 130 | JSONArray result = new JSONArray(); 131 | result.add(test); 132 | result.add(test); 133 | 134 | JSONObject response = new JSONObject(); 135 | response.put("result", result); 136 | return response.toString(); 137 | } 138 | 139 | @Test 140 | public void testGetMultiTests() throws Exception { 141 | LoggerTest logger = new LoggerTest(); 142 | UserNotifier notifier = new UserNotifierTest(); 143 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 144 | 145 | emul.addEmul(generateResponseGetMultiTests()); 146 | 147 | Workspace workspace = new Workspace(emul, "888", "workspace_name"); 148 | List multiTests = workspace.getMultiTests(); 149 | assertEquals(2, multiTests.size()); 150 | for (MultiTest t :multiTests) { 151 | assertEquals("999", t.getId()); 152 | assertEquals("MULTI_TEST", t.getName()); 153 | assertEquals("multi", t.getTestType()); 154 | } 155 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/multi-tests?workspaceId=888&sort%5B%5D=name&limit=10000, tag=null}", emul.getRequests().get(0)); 156 | String logs = logger.getLogs().toString(); 157 | assertEquals(logs, 329, logs.length()); 158 | assertTrue(logs, logs.contains("Get list of multi tests for workspace id=888")); 159 | } 160 | 161 | public static String generateResponseGetMultiTests() { 162 | JSONObject test = new JSONObject(); 163 | test.put("id", "999"); 164 | test.put("name", "MULTI_TEST"); 165 | test.put("collectionType", "multi"); 166 | 167 | JSONArray result = new JSONArray(); 168 | result.add(test); 169 | result.add(test); 170 | 171 | JSONObject response = new JSONObject(); 172 | response.put("result", result); 173 | return response.toString(); 174 | } 175 | 176 | @Test 177 | public void testFromJSON() throws Exception { 178 | LoggerTest logger = new LoggerTest(); 179 | UserNotifier notifier = new UserNotifierTest(); 180 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 181 | 182 | JSONObject object = new JSONObject(); 183 | object.put("id", "workspaceId"); 184 | object.put("name", "workspaceName"); 185 | Workspace workspace = Workspace.fromJSON(emul, object); 186 | assertEquals("workspaceId", workspace.getId()); 187 | assertEquals("workspaceName", workspace.getName()); 188 | } 189 | 190 | @Test 191 | public void testGetWorkspace() throws Exception { 192 | LoggerTest logger = new LoggerTest(); 193 | UserNotifier notifier = new UserNotifierTest(); 194 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 195 | 196 | emul.addEmul(generateResponseGetWorkspace()); 197 | 198 | Workspace workspace = Workspace.getWorkspace(emul, "123"); 199 | assertEquals("123", workspace.getId()); 200 | assertEquals("Default workspace", workspace.getName()); 201 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/workspaces/123, tag=null}", emul.getRequests().get(0)); 202 | String logs = logger.getLogs().toString(); 203 | assertEquals(logs, 186, logs.length()); 204 | assertTrue(logs, logs.contains("Get Workspace id=123")); 205 | } 206 | 207 | public static String generateResponseGetWorkspace() { 208 | JSONObject workspace = new JSONObject(); 209 | workspace.put("id", "123"); 210 | workspace.put("name", "Default workspace"); 211 | 212 | JSONObject response = new JSONObject(); 213 | response.put("result", workspace); 214 | return response.toString(); 215 | } 216 | 217 | @Test 218 | public void testGetTestSuites() throws Exception { 219 | LoggerTest logger = new LoggerTest(); 220 | UserNotifier notifier = new UserNotifierTest(); 221 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 222 | 223 | emul.addEmul(generateResponseGetTestSuites()); 224 | 225 | Workspace workspace = new Workspace(emul, "888", "workspace_name"); 226 | List multiTests = workspace.getTestSuite(); 227 | assertEquals(2, multiTests.size()); 228 | for (MultiTest t :multiTests) { 229 | assertEquals("456", t.getId()); 230 | assertEquals("TEST_SUITE", t.getName()); 231 | assertEquals("functionalTestSuite", t.getTestType()); 232 | } 233 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/multi-tests?workspaceId=888&platform=functional&sort%5B%5D=name&limit=10000, tag=null}", emul.getRequests().get(0)); 234 | String logs = logger.getLogs().toString(); 235 | assertEquals(logs, 376, logs.length()); 236 | assertTrue(logs, logs.contains("Get list of test suite for workspace id=888")); 237 | } 238 | 239 | public static String generateResponseGetTestSuites() { 240 | JSONObject test = new JSONObject(); 241 | test.put("id", "456"); 242 | test.put("name", "TEST_SUITE"); 243 | test.put("collectionType", "functionalTestSuite"); 244 | 245 | JSONArray result = new JSONArray(); 246 | result.add(test); 247 | result.add(test); 248 | 249 | JSONObject response = new JSONObject(); 250 | response.put("result", result); 251 | return response.toString(); 252 | } 253 | 254 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/http/HttpUtilsTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.http; 16 | 17 | import com.blazemeter.api.logging.LoggerTest; 18 | import net.sf.json.JSONObject; 19 | import okhttp3.*; 20 | import org.junit.Test; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.util.HashMap; 25 | import java.util.Map; 26 | 27 | import static com.blazemeter.api.http.HttpUtils.PROXY_HOST; 28 | import static com.blazemeter.api.http.HttpUtils.PROXY_PASS; 29 | import static com.blazemeter.api.http.HttpUtils.PROXY_PORT; 30 | import static com.blazemeter.api.http.HttpUtils.PROXY_USER; 31 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 32 | import static org.junit.Assert.assertEquals; 33 | import static org.junit.Assert.assertNotNull; 34 | import static org.junit.Assert.assertNull; 35 | import static org.junit.Assert.assertTrue; 36 | import static org.junit.Assert.fail; 37 | 38 | public class HttpUtilsTest { 39 | 40 | public static final String BLAZEDEMO = "http://blazedemo.com/"; 41 | 42 | @Test 43 | public void testRequests() throws Exception { 44 | LoggerTest logger = new LoggerTest(); 45 | 46 | HttpUtils utils = new HttpUtils(logger); 47 | Request get = utils.createGet(BZM_ADDRESS); 48 | assertEquals("GET", get.method()); 49 | assertEquals(BZM_ADDRESS + '/', get.url().toString()); 50 | 51 | RequestBody requestBody = RequestBody.create(MediaType.parse("UTF-8"), "param=value"); 52 | Request post1 = utils.createPost(BZM_ADDRESS, requestBody); 53 | assertEquals("POST", post1.method()); 54 | assertEquals(BZM_ADDRESS + '/', post1.url().toString()); 55 | assertEquals(11, post1.body().contentLength()); 56 | 57 | Request post2 = utils.createPost(BZM_ADDRESS, "{\"param\":\"value\"}"); 58 | assertEquals("POST", post2.method()); 59 | assertEquals(BZM_ADDRESS + '/', post2.url().toString()); 60 | assertEquals(17, post2.body().contentLength()); 61 | 62 | 63 | Request patch1 = utils.createPatch(BZM_ADDRESS, requestBody); 64 | assertEquals("PATCH", patch1.method()); 65 | assertEquals(BZM_ADDRESS + '/', patch1.url().toString()); 66 | assertEquals(11, patch1.body().contentLength()); 67 | 68 | Request patch2 = utils.createPatch(BZM_ADDRESS, "{\"param\":\"value\"}"); 69 | assertEquals("PATCH", patch2.method()); 70 | assertEquals(BZM_ADDRESS + '/', patch2.url().toString()); 71 | assertEquals(17, patch2.body().contentLength()); 72 | } 73 | 74 | @Test 75 | public void testGetters() throws Exception { 76 | LoggerTest logger = new LoggerTest(); 77 | HttpUtils utils = new HttpUtils(logger); 78 | utils.setLogger(logger); 79 | assertEquals(logger, utils.getLogger()); 80 | } 81 | 82 | @Test 83 | public void testModifiers() throws Exception { 84 | LoggerTest logger = new LoggerTest(); 85 | 86 | HttpUtils utils = new HttpUtils(logger); 87 | 88 | String response = "No response string"; 89 | assertEquals(response, utils.extractErrorMessage(response)); 90 | 91 | String url = BLAZEDEMO; 92 | assertEquals(url, utils.modifyRequestUrl(url)); 93 | Request.Builder builder = new Request.Builder().url(url).get(); 94 | Request request = utils.addRequiredHeader(builder).build(); 95 | assertEquals(0, request.headers().size()); 96 | String resp = utils.executeRequest(request); 97 | assertTrue(resp.length() > 0); 98 | assertTrue(resp.contains("BlazeMeter")); 99 | 100 | final String jsonResponse = "{\"param\":\"value\"}"; 101 | utils = new HttpUtils(logger) { 102 | @Override 103 | public String executeRequest(Request request) throws IOException { 104 | return jsonResponse; 105 | } 106 | }; 107 | JSONObject result = utils.execute(null); 108 | assertEquals(1, result.size()); 109 | assertEquals("value", result.getString("param")); 110 | } 111 | 112 | @Test 113 | public void testModifiers2() throws Exception { 114 | LoggerTest logger = new LoggerTest(); 115 | 116 | HttpUtils utils = new HttpUtils(logger) { 117 | @Override 118 | protected String modifyRequestUrl(String url) { 119 | return url + "additional_string"; 120 | } 121 | }; 122 | 123 | String url = BLAZEDEMO; 124 | assertEquals(url + "additional_string", utils.modifyRequestUrl(url)); 125 | } 126 | 127 | @Test 128 | public void testProxy() throws Exception { 129 | final Map saveProps = getProxyProps(); 130 | try { 131 | LoggerTest logger = new LoggerTest(); 132 | 133 | setProxyProps(BLAZEDEMO, "9999", "user1", "pass123456"); 134 | HttpUtils utils = new HttpUtils(logger); 135 | assertNotNull(utils); 136 | assertEquals("Using http.proxyHost = http://blazedemo.com/\r\n" + 137 | "Using http.proxyPort = 9999\r\n" + 138 | "Using http.proxyUser = user1\r\n" + 139 | "Using http.proxyPass = pass\r\n", logger.getLogs().toString()); 140 | logger.reset(); 141 | 142 | setProxyProps(BLAZEDEMO, "use default port", "", ""); 143 | utils = new HttpUtils(logger); 144 | assertNotNull(utils); 145 | assertEquals("Using http.proxyHost = http://blazedemo.com/\r\n" + 146 | "Failed to read http.proxyPort: \r\n" + 147 | "For input string: \"use default port\"\r\n" + 148 | "Using http.proxyUser = \r\n" + 149 | "Using http.proxyPass = \r\n", logger.getLogs().toString()); 150 | logger.reset(); 151 | 152 | try { 153 | setProxyProps("XXXX", "-12345", "", ""); 154 | new HttpUtils(logger); 155 | fail("Cannot init proxy with port '-12345'"); 156 | } catch (RuntimeException ex) { 157 | assertEquals("ERROR Instantiating HTTPClient. Exception received: port out of range:-12345", ex.getMessage()); 158 | assertEquals("Using http.proxyHost = XXXX\r\n" + 159 | "Using http.proxyPort = -12345\r\n" + 160 | "ERROR Instantiating HTTPClient. Exception received: port out of range:-12345\r\n" + 161 | "port out of range:-12345\r\n", logger.getLogs().toString()); 162 | } 163 | } finally { 164 | // return properties 165 | setProxyProps(saveProps.get(PROXY_HOST), 166 | saveProps.get(PROXY_PORT), 167 | saveProps.get(PROXY_USER), 168 | saveProps.get(PROXY_PASS)); 169 | } 170 | } 171 | 172 | private Map getProxyProps() { 173 | Map props = new HashMap<>(); 174 | props.put(PROXY_HOST, System.getProperty(PROXY_HOST)); 175 | props.put(PROXY_PORT, System.getProperty(PROXY_PORT)); 176 | props.put(PROXY_USER, System.getProperty(PROXY_USER)); 177 | props.put(PROXY_PASS, System.getProperty(PROXY_PASS)); 178 | return props; 179 | } 180 | 181 | private void setProxyProps(String host, String port, String user, String pass) { 182 | setPropertyOrClearIt(PROXY_HOST, host); 183 | setPropertyOrClearIt(PROXY_PORT, port); 184 | setPropertyOrClearIt(PROXY_USER, user); 185 | setPropertyOrClearIt(PROXY_PASS, pass); 186 | } 187 | 188 | private void setPropertyOrClearIt(String propertyName, String value) { 189 | if (value != null) { 190 | System.setProperty(propertyName, value); 191 | } else { 192 | System.clearProperty(propertyName); 193 | } 194 | } 195 | 196 | @Test 197 | public void testInterrupted() throws Exception { 198 | LoggerTest logger = new LoggerTest(); 199 | 200 | final HttpUtils utils = new HttpUtils(logger); 201 | 202 | final Request request = utils.createGet(BLAZEDEMO); 203 | Thread t = new Thread() { 204 | @Override 205 | public void run() { 206 | try { 207 | utils.executeRequest(request); 208 | fail(); 209 | } catch (Throwable e) { 210 | assertEquals("Request has been interrupted", e.getMessage()); 211 | } 212 | } 213 | }; 214 | t.start(); 215 | t.interrupt(); 216 | t.join(); 217 | } 218 | 219 | @Test 220 | public void testExecutionException() throws Exception { 221 | LoggerTest logger = new LoggerTest(); 222 | 223 | final HttpUtils utils = new HttpUtils(logger); 224 | 225 | final Request request = utils.createGet("http://aiaiaiaiaiaiaiiaxxxmsmsms.iiingo"); 226 | try { 227 | utils.executeRequest(request); 228 | fail(); 229 | } catch (Throwable e) { 230 | assertEquals("java.net.UnknownHostException: aiaiaiaiaiaiaiiaxxxmsmsms.iiingo: Name or service not known", e.getMessage()); 231 | } 232 | } 233 | 234 | @Test 235 | public void testAuth() throws Exception { 236 | HttpUtils.AuthenticatorExt auth = new HttpUtils.AuthenticatorExt("aaa", "xxx"); 237 | Request.Builder reqBuilder = new Request.Builder(); 238 | reqBuilder.url(BLAZEDEMO).get(); 239 | Response.Builder respBuilder = new Response.Builder(); 240 | respBuilder.request(reqBuilder.build()).protocol(Protocol.HTTP_1_1).code(200); 241 | Request actual = auth.authenticate(null, respBuilder.build()); 242 | assertEquals(actual.header("Proxy-Authorization"), "Basic YWFhOnh4eA=="); 243 | 244 | reqBuilder.addHeader("Proxy-Authorization", "aaa"); 245 | respBuilder.request(reqBuilder.build()); 246 | assertNull(auth.authenticate(null, respBuilder.build())); 247 | } 248 | 249 | @Test 250 | public void testPostFile() throws Exception { 251 | LoggerTest logger = new LoggerTest(); 252 | HttpUtils utils = new HttpUtils(logger); 253 | 254 | String path = HttpUtilsTest.class.getResource("/test.yml").getPath(); 255 | File file = new File(path); 256 | 257 | Request post = utils.createPost("http://blazedemo.com", file); 258 | RequestBody body = post.body(); 259 | assertEquals("multipart", body.contentType().type()); 260 | assertEquals("form-data", body.contentType().subtype()); 261 | assertTrue(body instanceof MultipartBody); 262 | 263 | MultipartBody.Part part = ((MultipartBody) body).part(0); 264 | assertEquals(149, part.body().contentLength()); 265 | assertEquals("application/x-www-form-urlencoded", part.body().contentType().toString()); 266 | } 267 | } -------------------------------------------------------------------------------- /src/test/java/com/blazemeter/api/explorer/SessionTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 BlazeMeter Inc. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | package com.blazemeter.api.explorer; 16 | 17 | import com.blazemeter.api.logging.LoggerTest; 18 | import com.blazemeter.api.logging.UserNotifier; 19 | import com.blazemeter.api.logging.UserNotifierTest; 20 | import com.blazemeter.api.utils.BlazeMeterUtilsEmul; 21 | import net.sf.json.JSONArray; 22 | import net.sf.json.JSONObject; 23 | import org.junit.Test; 24 | 25 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_ADDRESS; 26 | import static com.blazemeter.api.utils.BlazeMeterUtilsEmul.BZM_DATA_ADDRESS; 27 | import static org.junit.Assert.assertEquals; 28 | import static org.junit.Assert.assertNull; 29 | import static org.junit.Assert.assertTrue; 30 | import static org.junit.Assert.fail; 31 | 32 | public class SessionTest { 33 | 34 | @Test 35 | public void testPostProperties() throws Exception { 36 | LoggerTest logger = new LoggerTest(); 37 | UserNotifier notifier = new UserNotifierTest(); 38 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 39 | 40 | emul.addEmul(generateResponsePostProperties()); 41 | 42 | Session session = new Session(emul, "id", "name", "userId", "testId", "sign"); 43 | session.postProperties("key=url,value=google.com"); 44 | assertEquals("Request{method=POST, url=http://a.blazemeter.com/api/v4/sessions/id/properties?target=all, tag=null}", emul.getRequests().get(0)); 45 | String logs = logger.getLogs().toString(); 46 | assertEquals(logs, 213, logs.length()); 47 | assertTrue(logs, logs.contains("Post properties to session id=id")); 48 | } 49 | 50 | @Test 51 | public void testPostPropertiesEmpty() throws Exception { 52 | LoggerTest logger = new LoggerTest(); 53 | UserNotifier notifier = new UserNotifierTest(); 54 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 55 | 56 | emul.addEmul(generateResponsePostProperties()); 57 | 58 | Session session = new Session(emul, "id", "name", "userId", "testId", "sign"); 59 | session.postProperties(""); 60 | String logs = logger.getLogs().toString(); 61 | assertEquals(0, emul.getRequests().size()); 62 | assertEquals(logs, 53, logs.length()); 63 | assertTrue(logs, logs.contains("Properties are empty, won't be sent to session = ")); 64 | } 65 | 66 | public static String generateResponsePostProperties() { 67 | JSONObject property = new JSONObject(); 68 | property.put("key", "url"); 69 | property.put("value", "google.com"); 70 | 71 | JSONObject result = new JSONObject(); 72 | result.put("result", property); 73 | return result.toString(); 74 | } 75 | 76 | @Test 77 | public void testGetJTLReport() throws Exception { 78 | LoggerTest logger = new LoggerTest(); 79 | UserNotifier notifier = new UserNotifierTest(); 80 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 81 | 82 | emul.addEmul(generateResponseGetJTLReport()); 83 | 84 | Session session = new Session(emul, "id", "name", "userId", "testId", "sign"); 85 | String url = session.getJTLReport(); 86 | assertEquals("http://a.blazemeter.com/dataURL", url); 87 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/sessions/id/reports/logs, tag=null}", emul.getRequests().get(0)); 88 | String logs = logger.getLogs().toString(); 89 | assertEquals(logs, 244, logs.length()); 90 | assertTrue(logs, logs.contains("Get JTL report for session id=id")); 91 | } 92 | 93 | public static String generateResponseGetJTLReportWithRelativeUrl() { 94 | JSONObject dataUrl = new JSONObject(); 95 | dataUrl.put("dataUrl", "/api/veeeersion/sssss?file=sessions/sessionID/jtls_and_more.zip"); 96 | dataUrl.put("filename", "1.zip"); 97 | 98 | JSONArray data = new JSONArray(); 99 | data.add(dataUrl); 100 | 101 | JSONObject result = new JSONObject(); 102 | result.put("data", data); 103 | 104 | JSONObject response = new JSONObject(); 105 | response.put("result", result); 106 | return response.toString(); 107 | } 108 | 109 | public static String generateResponseGetJTLReport() { 110 | JSONObject dataUrl = new JSONObject(); 111 | dataUrl.put("dataUrl", "http://a.blazemeter.com/dataURL"); 112 | dataUrl.put("filename", "1.zip"); 113 | 114 | JSONArray data = new JSONArray(); 115 | data.add(dataUrl); 116 | 117 | JSONObject result = new JSONObject(); 118 | result.put("data", data); 119 | 120 | JSONObject response = new JSONObject(); 121 | response.put("result", result); 122 | return response.toString(); 123 | } 124 | 125 | public static String generateResponseGetJTLReportNullZip() { 126 | JSONObject dataUrl = new JSONObject(); 127 | dataUrl.put("dataUrl", "z"); 128 | dataUrl.put("filename", "x"); 129 | 130 | JSONArray data = new JSONArray(); 131 | data.add(dataUrl); 132 | 133 | JSONObject result = new JSONObject(); 134 | result.put("data", data); 135 | 136 | JSONObject response = new JSONObject(); 137 | response.put("result", result); 138 | return response.toString(); 139 | } 140 | 141 | @Test 142 | public void testGetJTLReportReturnNull() throws Exception { 143 | LoggerTest logger = new LoggerTest(); 144 | UserNotifier notifier = new UserNotifierTest(); 145 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 146 | 147 | emul.addEmul(generateResponseGetJTLReturnNull()); 148 | 149 | Session session = new Session(emul, "id", "name", "userId", "testId", "sign"); 150 | String url = session.getJTLReport(); 151 | assertNull(url); 152 | assertEquals("Request{method=GET, url=http://a.blazemeter.com/api/v4/sessions/id/reports/logs, tag=null}", emul.getRequests().get(0)); 153 | String logs = logger.getLogs().toString(); 154 | assertEquals(logs, 180, logs.length()); 155 | assertTrue(logs, logs.contains("Get JTL report for session id=id")); 156 | } 157 | 158 | public static String generateResponseGetJTLReturnNull() { 159 | JSONObject result = new JSONObject(); 160 | result.put("data", new JSONArray()); 161 | 162 | JSONObject response = new JSONObject(); 163 | response.put("result", result); 164 | return response.toString(); 165 | } 166 | 167 | @Test 168 | public void testTerminateExternal() throws Exception { 169 | LoggerTest logger = new LoggerTest(); 170 | UserNotifier notifier = new UserNotifierTest(); 171 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 172 | 173 | emul.addEmul("{}"); 174 | Session session = new Session(emul, "id", "name", "userId", "testId", "sign"); 175 | session.terminateExternal(); 176 | assertEquals("Request{method=POST, url=http://a.blazemeter.com/api/v4/sessions/id/terminate-external, tag=null}", emul.getRequests().get(0)); 177 | String logs = logger.getLogs().toString(); 178 | assertEquals(logs, 167, logs.length()); 179 | assertTrue(logs, logs.contains("Terminate external session id=id")); 180 | } 181 | 182 | @Test 183 | public void testSendData() throws Exception { 184 | LoggerTest logger = new LoggerTest(); 185 | UserNotifier notifier = new UserNotifierTest(); 186 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 187 | 188 | JSONObject data = new JSONObject(); 189 | data.put("data", "Hello, World!"); 190 | 191 | emul.addEmul("{\"result\":{\"session\":{\"statusCode\":15}}}"); 192 | 193 | Session session = new Session(emul, "sessionId", "sessionName", "userId", "testId", "testSignature"); 194 | session.sendData(data); 195 | 196 | assertEquals("Request{method=POST, url=http://data.blazemeter.com/submit.php?session_id=sessionId&signature=testSignature&test_id=testId&user_id=userId&pq=0&target=labels_bulk&update=1, tag=null}", emul.getRequests().get(0)); 197 | String logs = logger.getLogs().toString(); 198 | assertEquals(logs, 342, logs.length()); 199 | assertTrue(logs, logs.contains("Send data to session id=sessionId")); 200 | assertTrue(logs, logs.contains("Sending active test data: {\"data\":\"Hello, World!\"}")); 201 | } 202 | 203 | @Test 204 | public void testFromJSON() throws Exception { 205 | LoggerTest logger = new LoggerTest(); 206 | UserNotifier notifier = new UserNotifierTest(); 207 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 208 | 209 | JSONObject object = new JSONObject(); 210 | object.put("id", "sessionId"); 211 | object.put("name", "sessionName"); 212 | object.put("userId", "userId"); 213 | 214 | Session session = Session.fromJSON(emul, "testId", "signature", object); 215 | assertEquals("sessionId", session.getId()); 216 | assertEquals("sessionName", session.getName()); 217 | assertEquals("userId", session.getUserId()); 218 | assertEquals("testId", session.getTestId()); 219 | assertEquals("signature", session.getSignature()); 220 | } 221 | 222 | 223 | @Test 224 | public void testFromJSONNoSign() throws Exception { 225 | LoggerTest logger = new LoggerTest(); 226 | UserNotifier notifier = new UserNotifierTest(); 227 | BlazeMeterUtilsEmul emul = new BlazeMeterUtilsEmul(BZM_ADDRESS, BZM_DATA_ADDRESS, notifier, logger); 228 | 229 | JSONObject object = new JSONObject(); 230 | object.put("id", "id"); 231 | object.put("name", "name"); 232 | object.put("userId", "userId"); 233 | object.put("testId", "testId"); 234 | 235 | 236 | Session session = Session.fromJSON(emul, object); 237 | assertEquals("id", session.getId()); 238 | assertEquals("name", session.getName()); 239 | assertEquals("userId", session.getUserId()); 240 | assertEquals("testId", session.getTestId()); 241 | assertEquals(Session.UNDEFINED, session.getSignature()); 242 | } 243 | 244 | @Test 245 | public void convertProperties() { 246 | try { 247 | JSONArray array = Session.convertProperties("1=2,3=4"); 248 | assertEquals(2, array.size()); 249 | assertEquals(2, array.getJSONObject(0).size()); 250 | assertEquals("1", array.getJSONObject(0).getString("key")); 251 | assertEquals("2", array.getJSONObject(0).getString("value")); 252 | assertEquals(2, array.getJSONObject(1).size()); 253 | assertEquals("3", array.getJSONObject(1).getString("key")); 254 | assertEquals("4", array.getJSONObject(1).getString("value")); 255 | } catch (Exception e) { 256 | fail("Failed to convert properties to JSONArray"); 257 | } 258 | } 259 | } 260 | --------------------------------------------------------------------------------