Line data Source code
1 : // Copyright (C) 2013 The Android Open Source Project 2 : // 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 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.acceptance; 16 : 17 : import static com.google.common.truth.Truth.assertThat; 18 : import static com.google.common.truth.Truth.assertWithMessage; 19 : 20 : import com.google.gerrit.acceptance.testsuite.account.TestAccount; 21 : import com.google.gerrit.acceptance.testsuite.account.TestSshKeys; 22 : import java.io.Reader; 23 : import java.net.InetSocketAddress; 24 : 25 : public abstract class SshSession { 26 : protected final TestSshKeys sshKeys; 27 : protected final InetSocketAddress addr; 28 : protected final TestAccount account; 29 : protected String error; 30 : 31 132 : public SshSession(TestSshKeys sshKeys, InetSocketAddress addr, TestAccount account) { 32 132 : this.sshKeys = sshKeys; 33 132 : this.addr = addr; 34 132 : this.account = account; 35 132 : } 36 : 37 : public abstract void open() throws Exception; 38 : 39 : public abstract void close(); 40 : 41 : public abstract String exec(String command) throws Exception; 42 : 43 : public abstract int execAndReturnStatus(String command) throws Exception; 44 : 45 : public abstract Reader execAndReturnReader(String command) throws Exception; 46 : 47 : private boolean hasError() { 48 3 : return error != null; 49 : } 50 : 51 : public String getError() { 52 3 : return error; 53 : } 54 : 55 : public void assertSuccess() { 56 3 : assertWithMessage(getError()).that(hasError()).isFalse(); 57 3 : } 58 : 59 : public void assertFailure() { 60 1 : assertThat(hasError()).isTrue(); 61 1 : } 62 : 63 : public void assertFailure(String error) { 64 1 : assertThat(hasError()).isTrue(); 65 1 : assertThat(getError()).contains(error); 66 1 : } 67 : 68 : public String getUrl() { 69 2 : StringBuilder b = new StringBuilder(); 70 2 : b.append("ssh://"); 71 2 : b.append(account.username().get()); 72 2 : b.append("@"); 73 2 : b.append(addr.getAddress().getHostAddress()); 74 2 : b.append(":"); 75 2 : b.append(addr.getPort()); 76 2 : return b.toString(); 77 : } 78 : 79 : protected String getUsername() { 80 13 : return account 81 13 : .username() 82 13 : .orElseThrow( 83 : () -> 84 0 : new IllegalStateException( 85 0 : "account " + account.accountId() + " must have a username to use SSH")); 86 : } 87 : }