How to use method of org.easymock.EasyMock class

Best Easymock code snippet using org.easymock.EasyMock.

Run Easymock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/*******************************************************************************
2 * Copyright (c) 2011, 2017 SAP AG and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 * 
8 * Contributors:
9 *     Lazar Kirchev, SAP AG - initial API and implementation
10 *******************************************************************************/
11package org.eclipse.equinox.console.telnet;
12
13import static org.junit.Assert.fail;
14
15import java.io.IOException;
16import java.io.OutputStream;
17import java.io.PrintStream;
18import java.net.Socket;
19import java.util.Dictionary;
20import java.util.Hashtable;
21
22import org.apache.felix.service.command.CommandProcessor;
23import org.apache.felix.service.command.CommandSession;
24import org.easymock.EasyMock;
25import org.eclipse.equinox.console.common.ConsoleInputStream;
26import org.junit.Test;
27import org.osgi.framework.BundleContext;
28import org.osgi.framework.ServiceRegistration;
29import org.osgi.service.cm.ManagedService;
30
31
32public class TelnetCommandWithConfigAdminTests {
33	private static final int TEST_CONTENT = 100;
34	private static final String STOP_COMMAND = "stop";
35	private static final String HOST = "localhost";
36	private static final String TELNET_PORT = "2223";
37	private static final long WAIT_TIME = 5000;
38	private static final String USE_CONFIG_ADMIN_PROP = "osgi.console.useConfigAdmin";
39	private static final String TRUE = "true";
40	private static final String FALSE = "false";
41	private ManagedService configurator;
42	
43	@Test
44	public void testTelnetCommandWithConfigAdminEnabledTelnet() throws Exception {
45		CommandSession session = EasyMock.createMock(CommandSession.class);
46    	session.put((String)EasyMock.anyObject(), EasyMock.anyObject());
47        EasyMock.expectLastCall().times(3);
48        EasyMock.expect(session.execute((String)EasyMock.anyObject())).andReturn(new Object());
49        session.close();
50		EasyMock.expectLastCall();
51        EasyMock.replay(session);
52        
53        CommandProcessor processor = EasyMock.createMock(CommandProcessor.class);
54        EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session);
55        EasyMock.replay(processor);
56
57        final ServiceRegistration<?> registration = EasyMock.createMock(ServiceRegistration.class);
58        registration.setProperties((Dictionary<String, ?>)EasyMock.anyObject());
59
60        EasyMock.expectLastCall();
61        EasyMock.replay(registration);
62
63        BundleContext context = EasyMock.createMock(BundleContext.class);
64        EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(TRUE);
65        EasyMock.expect(
66        		(ServiceRegistration) context.registerService(
67        				(String)EasyMock.anyObject(), 
68        				(ManagedService)EasyMock.anyObject(), 
69        				(Dictionary<String, ?>)EasyMock.anyObject())
70        	).andAnswer(() -> {
71				configurator = (ManagedService) EasyMock.getCurrentArguments()[1];
72				return registration;
73			});
74        EasyMock.expect(
75        		context.registerService(
76        				(String)EasyMock.anyObject(), 
77        				(TelnetCommand)EasyMock.anyObject(), 
78        				(Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null);
79        EasyMock.replay(context);
80        
81        TelnetCommand command = new TelnetCommand(processor, context);
82        command.startService();
83        Dictionary<String, String> props = new Hashtable<>();
84		props.put("port", TELNET_PORT);
85		props.put("host", HOST);
86		props.put("enabled", TRUE);
87		configurator.updated(props);
88		
89        try (Socket socketClient = new Socket(HOST, Integer.parseInt(TELNET_PORT));){
90            OutputStream outClient = socketClient.getOutputStream();
91            outClient.write(TEST_CONTENT);
92            outClient.write('\n');
93            outClient.flush();
94
95            // wait for the accept thread to finish execution
96            try {
97                Thread.sleep(WAIT_TIME);
98            } catch (InterruptedException ie) {
99                // do nothing
100            }
101        } finally {
102            command.telnet(new String[] {STOP_COMMAND});
103        }
104        EasyMock.verify(context);
105	}
106	
107	@Test
108	public void testTelnetCommandWithConfigAdminDisabledTelnet() throws Exception {
109		disabledTelnet(false);
110	}
111	
112	@Test
113	public void testTelnetCommandWithConfigAdminDisabledTelnetByDefault() throws Exception {
114		disabledTelnet(true);
115	}
116	
117	private void disabledTelnet(boolean isDefault) throws Exception {
118		CommandSession session = EasyMock.createMock(CommandSession.class);
119    	session.put((String)EasyMock.anyObject(), EasyMock.anyObject());
120        EasyMock.expectLastCall().times(4);
121        EasyMock.expect(session.execute((String)EasyMock.anyObject())).andReturn(new Object());
122        session.close();
123		EasyMock.expectLastCall();
124        EasyMock.replay(session);
125        
126        CommandProcessor processor = EasyMock.createMock(CommandProcessor.class);
127        EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session);
128        EasyMock.replay(processor);
129
130        final ServiceRegistration<?> registration = EasyMock.createMock(ServiceRegistration.class);
131        registration.setProperties((Dictionary<String, ?>)EasyMock.anyObject());
132
133        EasyMock.expectLastCall();
134        EasyMock.replay(registration);
135
136        BundleContext context = EasyMock.createMock(BundleContext.class);
137        EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(TRUE);
138        EasyMock.expect(
139        		(ServiceRegistration) context.registerService(
140        				(String)EasyMock.anyObject(), 
141        				(ManagedService)EasyMock.anyObject(), 
142        				(Dictionary<String, ?>)EasyMock.anyObject())
143        	).andAnswer(() -> {
144				configurator = (ManagedService) EasyMock.getCurrentArguments()[1];
145				return registration;
146			});
147        EasyMock.expect(
148        		context.registerService(
149        				(String)EasyMock.anyObject(), 
150        				(TelnetCommand)EasyMock.anyObject(), 
151        				(Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null);
152        EasyMock.replay(context);
153        
154        TelnetCommand command = new TelnetCommand(processor, context);
155        command.startService();
156        Dictionary<String, String> props = new Hashtable<>();
157		props.put("port", TELNET_PORT);
158		props.put("host", HOST);
159		if (isDefault == false) {
160			props.put("enabled", FALSE);
161		}
162		configurator.updated(props);
163		
164        try (Socket socketClient = new Socket(HOST, Integer.parseInt(TELNET_PORT))){
165            
166            fail("It should not be possible to open a socket to " + HOST + ":" + TELNET_PORT);
167        } catch (IOException e) {
168        	// this is ok, there should be an exception
169        } finally {
170            try {
171            	command.telnet(new String[] {STOP_COMMAND});
172            } catch (IllegalStateException e) {
173            	//this is expected
174            }
175        }
176        EasyMock.verify(context);
177	}
178	
179}
180
Full Screen
copy
1/*
2 * Copyright (C) 2011 The Android Open Source Project
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 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.mediaframeworktest.unit;
18
19import android.content.ContentValues;
20import android.content.IContentProvider;
21import android.media.MediaInserter;
22import android.net.Uri;
23import android.provider.MediaStore.Audio;
24import android.provider.MediaStore.Files;
25import android.provider.MediaStore.Images;
26import android.provider.MediaStore.Video;
27import android.test.InstrumentationTestCase;
28import android.test.suitebuilder.annotation.SmallTest;
29
30import dalvik.annotation.TestTargetClass;
31
32import org.easymock.EasyMock;
33import org.easymock.IArgumentMatcher;
34
35@TestTargetClass(MediaInserter.class)
36public class MediaInserterTest extends InstrumentationTestCase {
37
38    private MediaInserter mMediaInserter;
39    private static final int TEST_BUFFER_SIZE = 10;
40    private IContentProvider mMockProvider;
41    private String mPackageName;
42
43    private int mFilesCounter;
44    private int mAudioCounter;
45    private int mVideoCounter;
46    private int mImagesCounter;
47
48    private static final String sVolumeName = "external";
49    private static final Uri sAudioUri = Audio.Media.getContentUri(sVolumeName);
50    private static final Uri sVideoUri = Video.Media.getContentUri(sVolumeName);
51    private static final Uri sImagesUri = Images.Media.getContentUri(sVolumeName);
52    private static final Uri sFilesUri = Files.getContentUri(sVolumeName);
53
54    private static class MediaUriMatcher implements IArgumentMatcher {
55        private Uri mUri;
56
57        private MediaUriMatcher(Uri uri) {
58            mUri = uri;
59        }
60
61        @Override
62        public boolean matches(Object argument) {
63            if (!(argument instanceof Uri)) {
64                return false;
65            }
66
67            Uri actualUri = (Uri) argument;
68            if (actualUri == mUri) return true;
69            return false;
70        }
71
72        @Override
73        public void appendTo(StringBuffer buffer) {
74            buffer.append("expected a TableUri '").append(mUri).append("'");
75        }
76
77        private static Uri expectMediaUri(Uri in) {
78            EasyMock.reportMatcher(new MediaUriMatcher(in));
79            return null;
80        }
81    }
82
83    @Override
84    protected void setUp() throws Exception {
85        super.setUp();
86        mMockProvider = EasyMock.createMock(IContentProvider.class);
87        mMediaInserter = new MediaInserter(mMockProvider,
88		mPackageName, TEST_BUFFER_SIZE);
89	mPackageName = getInstrumentation().getContext().getPackageName();
90        mFilesCounter = 0;
91        mAudioCounter = 0;
92        mVideoCounter = 0;
93        mImagesCounter = 0;
94    }
95
96    private ContentValues createFileContent() {
97        ContentValues values = new ContentValues();
98        values.put("_data", "/mnt/sdcard/file" + ++mFilesCounter);
99        return values;
100    }
101
102    private ContentValues createAudioContent() {
103        ContentValues values = new ContentValues();
104        values.put("_data", "/mnt/sdcard/audio" + ++mAudioCounter);
105        return values;
106    }
107
108    private ContentValues createVideoContent() {
109        ContentValues values = new ContentValues();
110        values.put("_data", "/mnt/sdcard/video" + ++mVideoCounter);
111        return values;
112    }
113
114    private ContentValues createImageContent() {
115        ContentValues values = new ContentValues();
116        values.put("_data", "/mnt/sdcard/image" + ++mImagesCounter);
117        return values;
118    }
119
120    private ContentValues createContent(Uri uri) {
121        if (uri == sFilesUri) return createFileContent();
122        else if (uri == sAudioUri) return createAudioContent();
123        else if (uri == sVideoUri) return createVideoContent();
124        else if (uri == sImagesUri) return createImageContent();
125        else throw new IllegalArgumentException("Unknown URL: " + uri.toString());
126    }
127
128    private void fillBuffer(Uri uri, int numberOfFiles) throws Exception {
129        ContentValues values;
130        for (int i = 0; i < numberOfFiles; ++i) {
131            values = createContent(uri);
132            mMediaInserter.insert(uri, values);
133        }
134    }
135
136    @SmallTest
137    public void testInsertContentsLessThanBufferSize() throws Exception {
138        EasyMock.replay(mMockProvider);
139
140        fillBuffer(sFilesUri, TEST_BUFFER_SIZE - 4);
141        fillBuffer(sAudioUri, TEST_BUFFER_SIZE - 3);
142        fillBuffer(sVideoUri, TEST_BUFFER_SIZE - 2);
143        fillBuffer(sImagesUri, TEST_BUFFER_SIZE - 1);
144
145        EasyMock.verify(mMockProvider);
146    }
147
148    @SmallTest
149    public void testInsertContentsEqualToBufferSize() throws Exception {
150        EasyMock.expect(mMockProvider.bulkInsert(mPackageName,
151                (Uri) EasyMock.anyObject(), (ContentValues[]) EasyMock.anyObject())).andReturn(1);
152        EasyMock.expectLastCall().times(4);
153        EasyMock.replay(mMockProvider);
154
155        fillBuffer(sFilesUri, TEST_BUFFER_SIZE);
156        fillBuffer(sAudioUri, TEST_BUFFER_SIZE);
157        fillBuffer(sVideoUri, TEST_BUFFER_SIZE);
158        fillBuffer(sImagesUri, TEST_BUFFER_SIZE);
159
160        EasyMock.verify(mMockProvider);
161    }
162
163    @SmallTest
164    public void testInsertContentsMoreThanBufferSize() throws Exception {
165        EasyMock.expect(mMockProvider.bulkInsert(mPackageName,
166                (Uri) EasyMock.anyObject(), (ContentValues[]) EasyMock.anyObject())).andReturn(1);
167        EasyMock.expectLastCall().times(4);
168        EasyMock.replay(mMockProvider);
169
170        fillBuffer(sFilesUri, TEST_BUFFER_SIZE + 1);
171        fillBuffer(sAudioUri, TEST_BUFFER_SIZE + 2);
172        fillBuffer(sVideoUri, TEST_BUFFER_SIZE + 3);
173        fillBuffer(sImagesUri, TEST_BUFFER_SIZE + 4);
174
175        EasyMock.verify(mMockProvider);
176    }
177
178    @SmallTest
179    public void testFlushAllWithEmptyContents() throws Exception {
180        EasyMock.replay(mMockProvider);
181
182        mMediaInserter.flushAll();
183
184        EasyMock.verify(mMockProvider);
185    }
186
187    @SmallTest
188    public void testFlushAllWithSomeContents() throws Exception {
189        EasyMock.expect(mMockProvider.bulkInsert(mPackageName,
190                (Uri) EasyMock.anyObject(), (ContentValues[]) EasyMock.anyObject())).andReturn(1);
191        EasyMock.expectLastCall().times(4);
192        EasyMock.replay(mMockProvider);
193
194        fillBuffer(sFilesUri, TEST_BUFFER_SIZE - 4);
195        fillBuffer(sAudioUri, TEST_BUFFER_SIZE - 3);
196        fillBuffer(sVideoUri, TEST_BUFFER_SIZE - 2);
197        fillBuffer(sImagesUri, TEST_BUFFER_SIZE - 1);
198        mMediaInserter.flushAll();
199
200        EasyMock.verify(mMockProvider);
201    }
202
203    @SmallTest
204    public void testInsertContentsAfterFlushAll() throws Exception {
205        EasyMock.expect(mMockProvider.bulkInsert(mPackageName,
206                (Uri) EasyMock.anyObject(), (ContentValues[]) EasyMock.anyObject())).andReturn(1);
207        EasyMock.expectLastCall().times(8);
208        EasyMock.replay(mMockProvider);
209
210        fillBuffer(sFilesUri, TEST_BUFFER_SIZE - 4);
211        fillBuffer(sAudioUri, TEST_BUFFER_SIZE - 3);
212        fillBuffer(sVideoUri, TEST_BUFFER_SIZE - 2);
213        fillBuffer(sImagesUri, TEST_BUFFER_SIZE - 1);
214        mMediaInserter.flushAll();
215
216        fillBuffer(sFilesUri, TEST_BUFFER_SIZE + 1);
217        fillBuffer(sAudioUri, TEST_BUFFER_SIZE + 2);
218        fillBuffer(sVideoUri, TEST_BUFFER_SIZE + 3);
219        fillBuffer(sImagesUri, TEST_BUFFER_SIZE + 4);
220
221        EasyMock.verify(mMockProvider);
222    }
223
224    @SmallTest
225    public void testInsertContentsWithDifferentSizePerContentType() throws Exception {
226        EasyMock.expect(mMockProvider.bulkInsert(mPackageName,
227		MediaUriMatcher.expectMediaUri(sFilesUri),
228                (ContentValues[]) EasyMock.anyObject())).andReturn(1);
229        EasyMock.expectLastCall().times(1);
230        EasyMock.expect(mMockProvider.bulkInsert(mPackageName,
231		MediaUriMatcher.expectMediaUri(sAudioUri),
232                (ContentValues[]) EasyMock.anyObject())).andReturn(1);
233        EasyMock.expectLastCall().times(2);
234        EasyMock.expect(mMockProvider.bulkInsert(mPackageName,
235		MediaUriMatcher.expectMediaUri(sVideoUri),
236                (ContentValues[]) EasyMock.anyObject())).andReturn(1);
237        EasyMock.expectLastCall().times(3);
238        EasyMock.expect(mMockProvider.bulkInsert(mPackageName,
239		MediaUriMatcher.expectMediaUri(sImagesUri),
240                (ContentValues[]) EasyMock.anyObject())).andReturn(1);
241        EasyMock.expectLastCall().times(4);
242        EasyMock.replay(mMockProvider);
243
244        for (int i = 0; i < TEST_BUFFER_SIZE; ++i) {
245            fillBuffer(sFilesUri, 1);
246            fillBuffer(sAudioUri, 2);
247            fillBuffer(sVideoUri, 3);
248            fillBuffer(sImagesUri, 4);
249        }
250
251        EasyMock.verify(mMockProvider);
252    }
253}
254
Full Screen
copy
1/*******************************************************************************
2 * Copyright (c) 2011 SAP AG
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 * 
8 * Contributors:
9 *     Lazar Kirchev, SAP AG - initial API and implementation
10 *******************************************************************************/
11package org.eclipse.equinox.console.ssh;
12
13import java.io.ByteArrayOutputStream;
14import java.io.File;
15import java.io.InputStream;
16import java.io.PrintStream;
17import java.io.PrintWriter;
18import java.io.StringBufferInputStream;
19import java.util.Collection;
20import java.util.Dictionary;
21import java.util.HashMap;
22import java.util.Hashtable;
23import java.util.Map;
24
25import org.apache.felix.service.command.CommandProcessor;
26import org.apache.felix.service.command.CommandSession;
27import org.apache.sshd.ClientChannel;
28import org.apache.sshd.ClientSession;
29import org.apache.sshd.SshClient;
30import org.apache.sshd.client.future.ConnectFuture;
31import org.apache.sshd.client.future.DefaultConnectFuture;
32import org.apache.sshd.common.RuntimeSshException;
33import org.apache.sshd.server.Environment;
34import org.easymock.EasyMock;
35import org.easymock.IAnswer;
36import org.eclipse.equinox.console.common.ConsoleInputStream;
37import org.eclipse.equinox.console.storage.DigestUtil;
38import org.eclipse.equinox.console.storage.SecureUserStore;
39import org.junit.After;
40import org.junit.Assert;
41import org.junit.Before;
42import org.junit.Test;
43import org.osgi.framework.Bundle;
44import org.osgi.framework.BundleContext;
45import org.osgi.framework.BundleException;
46import org.osgi.framework.BundleListener;
47import org.osgi.framework.Filter;
48import org.osgi.framework.FrameworkListener;
49import org.osgi.framework.InvalidSyntaxException;
50import org.osgi.framework.ServiceListener;
51import org.osgi.framework.ServiceReference;
52import org.osgi.framework.ServiceRegistration;
53import org.osgi.service.cm.ManagedService;
54
55
56public class SshCommandWithConfigAdminTests {
57	private static final int TEST_CONTENT = 100;
58	private static final String USER_STORE_FILE_NAME = "org.eclipse.equinox.console.jaas.file";
59	private static final String JAAS_CONFIG_FILE_NAME = "jaas.config";
60	private static final String JAAS_CONFIG_PROPERTY_NAME = "java.security.auth.login.config";
61	private static final String DEFAULT_USER_STORAGE = "osgi.console.ssh.useDefaultSecureStorage";
62	private static final String STORE_FILE_NAME = SshCommandTests.class.getName() + "_store";
63	private static final String GOGO_SHELL_COMMAND = "gosh --login --noshutdown";
64	private static final String TRUE = "true";
65	private static final String FALSE = "false";
66	private static final String USERNAME = "username";
67	private static final String PASSWORD = "password";
68	private static final String STOP_COMMAND = "stop";
69	private static final String TERM_PROPERTY = "TERM";
70	private static final String XTERM = "XTERM";
71	private static final String HOST = "localhost";
72	private static final String SSH_PORT = "2222";
73	private static final long WAIT_TIME = 5000;
74	private static final String USE_CONFIG_ADMIN_PROP = "osgi.console.useConfigAdmin";
75	private ManagedService configurator;
76
77	@Before
78	public void init() throws Exception {
79		clean();
80		initStore();
81        initJaasConfigFile();
82	}
83	
84	@Test
85	public void testSshCommandWithConfigAdmin() throws Exception {
86		
87		CommandSession session = EasyMock.createMock(CommandSession.class);
88		EasyMock.makeThreadSafe(session, true);
89		session.put((String)EasyMock.anyObject(), EasyMock.anyObject());
90		EasyMock.expectLastCall().times(5);
91		EasyMock.expect(session.execute(GOGO_SHELL_COMMAND)).andReturn(null);
92		session.close();
93		EasyMock.expectLastCall();
94		EasyMock.replay(session);
95
96		CommandProcessor processor = EasyMock.createMock(CommandProcessor.class);
97		EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session);
98		EasyMock.replay(processor);
99
100		final ServiceRegistration<?> registration = EasyMock.createMock(ServiceRegistration.class);
101        registration.setProperties((Dictionary)EasyMock.anyObject());
102        EasyMock.expectLastCall();
103        EasyMock.replay(registration);
104
105        BundleContext context = EasyMock.createMock(BundleContext.class);
106        EasyMock.makeThreadSafe(context, true);
107        EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(TRUE);
108		EasyMock.expect(context.getProperty(DEFAULT_USER_STORAGE)).andReturn(TRUE).anyTimes();
109        EasyMock.expect(
110        		(ServiceRegistration) context.registerService(
111        				(String)EasyMock.anyObject(), 
112        				(ManagedService)EasyMock.anyObject(), 
113        				(Dictionary<String, ?>)EasyMock.anyObject())
114        	).andAnswer((IAnswer<ServiceRegistration<?>>) new IAnswer<ServiceRegistration<?>>() {
115        		public ServiceRegistration<?> answer() {
116        			configurator = (ManagedService) EasyMock.getCurrentArguments()[1];
117        			return registration;
118        		}
119			});
120        EasyMock.expect(
121        		context.registerService(
122        				(String)EasyMock.anyObject(), 
123        				(SshCommand)EasyMock.anyObject(), 
124        				(Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null);
125		EasyMock.replay(context);
126
127		Map<String, String> environment = new HashMap<String, String>();
128		environment.put(TERM_PROPERTY, XTERM);
129		Environment env = EasyMock.createMock(Environment.class);
130		EasyMock.expect(env.getEnv()).andReturn(environment);
131		EasyMock.replay(env);
132
133		SshCommand command = new SshCommand(processor, context);
134		Dictionary props = new Hashtable();
135		props.put("port", SSH_PORT);
136		props.put("host", HOST);
137		props.put("enabled", TRUE);
138		configurator.updated(props);
139
140		SshClient client = SshClient.setUpDefaultClient();
141		client.start();
142		try {
143			ConnectFuture connectFuture = client.connect(HOST, Integer.valueOf(SSH_PORT));
144			DefaultConnectFuture defaultConnectFuture = (DefaultConnectFuture) connectFuture;
145
146			try {
147				Thread.sleep(WAIT_TIME);
148			} catch (InterruptedException ie) {
149				// do nothing
150			}
151			ClientSession sshSession = defaultConnectFuture.getSession();
152
153			int ret = ClientSession.WAIT_AUTH;                
154			sshSession.authPassword(USERNAME, PASSWORD);
155			ret = sshSession.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
156
157			if ((ret & ClientSession.CLOSED) != 0) {
158				System.err.println("error");
159				System.exit(-1);
160			}
161			ClientChannel channel = sshSession.createChannel("shell");
162			channel.setIn(new StringBufferInputStream(TEST_CONTENT + "\n"));
163			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
164			channel.setOut(byteOut);
165			channel.setErr(byteOut);
166			channel.open();
167			try {
168				Thread.sleep(WAIT_TIME);
169			} catch (InterruptedException ie) {
170				// do nothing
171			}
172			byte[] output = byteOut.toByteArray();
173			Assert.assertEquals("Output not as expected",Integer.toString(TEST_CONTENT), new String(output).trim());
174			sshSession.close(true);
175		} finally {
176			client.stop();
177		}
178
179		command.ssh(new String[] {STOP_COMMAND});
180		return;
181	}
182	
183	@Test
184	public void testSshCommandWithConfigAdminDisabledSsh() throws Exception {
185		testDisabled(false);
186	}
187	
188	@Test
189	public void testSshCommandWithConfigAdminDisabledSshByDefault() throws Exception {
190		testDisabled(true);
191	}
192	
193	private void testDisabled(boolean isDefault) throws Exception {
194		CommandSession session = EasyMock.createMock(CommandSession.class);
195		session.put((String)EasyMock.anyObject(), EasyMock.anyObject());
196		EasyMock.expectLastCall().times(4);
197		EasyMock.expect(session.execute(GOGO_SHELL_COMMAND)).andReturn(null);
198		session.close();
199		EasyMock.expectLastCall();
200		EasyMock.replay(session);
201
202		CommandProcessor processor = EasyMock.createMock(CommandProcessor.class);
203		EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session);
204		EasyMock.replay(processor);
205
206		final ServiceRegistration<?> registration = EasyMock.createMock(ServiceRegistration.class);
207        registration.setProperties((Dictionary)EasyMock.anyObject());
208        EasyMock.expectLastCall();
209        EasyMock.replay(registration);
210
211        BundleContext context = EasyMock.createMock(BundleContext.class);
212        EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(TRUE);
213		EasyMock.expect(context.getProperty(DEFAULT_USER_STORAGE)).andReturn(TRUE).anyTimes();
214        EasyMock.expect(
215        		(ServiceRegistration) context.registerService(
216        				(String)EasyMock.anyObject(), 
217        				(ManagedService)EasyMock.anyObject(), 
218        				(Dictionary<String, ?>)EasyMock.anyObject())
219        	).andAnswer((IAnswer<ServiceRegistration<?>>) new IAnswer<ServiceRegistration<?>>() {
220        		public ServiceRegistration<?> answer() {
221        			configurator = (ManagedService) EasyMock.getCurrentArguments()[1];
222        			return registration;
223        		}
224			});
225        EasyMock.expect(
226        		context.registerService(
227        				(String)EasyMock.anyObject(), 
228        				(SshCommand)EasyMock.anyObject(), 
229        				(Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null);
230		EasyMock.replay(context);
231
232		Map<String, String> environment = new HashMap<String, String>();
233		environment.put(TERM_PROPERTY, XTERM);
234		Environment env = EasyMock.createMock(Environment.class);
235		EasyMock.expect(env.getEnv()).andReturn(environment);
236		EasyMock.replay(env);
237
238		SshCommand command = new SshCommand(processor, context);
239		Dictionary props = new Hashtable();
240		props.put("port", SSH_PORT);
241		props.put("host", HOST);
242		if (isDefault == false) {
243			props.put("enabled", FALSE);
244		}
245		configurator.updated(props);
246
247		SshClient client = SshClient.setUpDefaultClient();
248		client.start();
249		try {
250			ConnectFuture connectFuture = client.connect(HOST, Integer.valueOf(SSH_PORT));
251			DefaultConnectFuture defaultConnectFuture = (DefaultConnectFuture) connectFuture;
252
253			try {
254				Thread.sleep(WAIT_TIME);
255			} catch (InterruptedException ie) {
256				// do nothing
257			}
258			ClientSession sshSession;
259			try {
260				sshSession = defaultConnectFuture.getSession();
261				Assert.fail("It should not be possible to connect to " + HOST + ":" + SSH_PORT);
262			} catch (RuntimeSshException e) {
263				//this is expected
264			}
265		} finally {
266			client.stop();
267		}
268
269		try {
270			command.ssh(new String[] {STOP_COMMAND});
271		} catch (IllegalStateException e) {
272			// this is expected
273		}
274		return;
275	}
276	
277	@After
278	public void cleanUp() {
279		clean();
280	}
281	
282	private void clean() {
283		System.setProperty(USER_STORE_FILE_NAME, "");
284    	File file = new File(STORE_FILE_NAME);
285    	if (file.exists()) {
286    		file.delete();
287    	}
288    	
289    	System.setProperty(JAAS_CONFIG_PROPERTY_NAME, "");
290    	File jaasConfFile = new File(JAAS_CONFIG_FILE_NAME);
291    	if (jaasConfFile.exists()) {
292    		jaasConfFile.delete();
293    	}
294	}
295	
296	private void initStore() throws Exception {
297		System.setProperty(USER_STORE_FILE_NAME, STORE_FILE_NAME);
298        SecureUserStore.initStorage();
299        SecureUserStore.putUser(USERNAME, DigestUtil.encrypt(PASSWORD), null);
300	}
301	
302	private void initJaasConfigFile() throws Exception {
303		System.setProperty(JAAS_CONFIG_PROPERTY_NAME, JAAS_CONFIG_FILE_NAME);
304		File jaasConfFile = new File(JAAS_CONFIG_FILE_NAME);
305    	if (!jaasConfFile.exists()) {
306    		PrintWriter out = null;
307    		try {
308				out = new PrintWriter(jaasConfFile);
309				out.println("equinox_console {");
310				out.println("	org.eclipse.equinox.console.jaas.SecureStorageLoginModule REQUIRED;");
311				out.println("};");
312			} finally {
313				if (out != null) {
314					out.close();
315				}
316			}
317    	}
318	}
319	
320}
321
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)