使用Apache Mina作为模拟/内存SFTP服务器进行单元测试
问题描述:
我在处理如何使用Apache Mina时遇到了一些麻烦。他们的文档对于我的无能的大脑来说是有点缺乏的。我看到有用的起始代码在 Java SFTP server library?使用Apache Mina作为模拟/内存SFTP服务器进行单元测试
我无法弄清楚的是如何使用它。我想设置一个单元测试,检查我的SFTP代码,使用米娜作为一种模拟服务器,即,能够编写单元测试,如:
@Before
public void beforeTestSetup() {
sshd = SshServer.setUpDefaultServer();
sshd.setPort(22);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>();
userAuthFactories.add(new UserAuthNone.Factory());
sshd.setUserAuthFactories(userAuthFactories);
sshd.setPublickeyAuthenticator(new PublickeyAuthenticator());
sshd.setCommandFactory(new ScpCommandFactory());
List<NamedFactory<Command>> namedFactoryList = new ArrayList<NamedFactory<Command>>();
namedFactoryList.add(new SftpSubsystem.Factory());
sshd.setSubsystemFactories(namedFactoryList);
try {
sshd.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetFile() {
}
的问题是要放什么testGetFile()
。
我一直在测试通过测试代码,想知道在上面是否需要更多的配置来指定根目录,用户名和认证密钥文件名。那么我需要使用客户端或我自己的SFTP API代码来从中获取文件?
我确定这是一个很好的API,没有太多的指导,任何人都可以帮忙吗?
答
这里是我做的测试(JUnit):
@Test
public void testPutAndGetFile() throws JSchException, SftpException, IOException
{
JSch jsch = new JSch();
Hashtable<String, String> config = new Hashtable<String, String>();
config.put("StrictHostKeyChecking", "no");
JSch.setConfig(config);
Session session = jsch.getSession("remote-username", "localhost", PORT);
session.setPassword("remote-password");
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
final String testFileContents = "some file contents";
String uploadedFileName = "uploadFile";
sftpChannel.put(new ByteArrayInputStream(testFileContents.getBytes()), uploadedFileName);
String downloadedFileName = "downLoadFile";
sftpChannel.get(uploadedFileName, downloadedFileName);
File downloadedFile = new File(downloadedFileName);
Assert.assertTrue(downloadedFile.exists());
String fileData = getFileContents(downloadedFile);
Assert.assertEquals(testFileContents, fileData);
if (sftpChannel.isConnected()) {
sftpChannel.exit();
System.out.println("Disconnected channel");
}
if (session.isConnected()) {
session.disconnect();
System.out.println("Disconnected session");
}
}
private String getFileContents(File downloadedFile)
throws FileNotFoundException, IOException
{
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(downloadedFile));
try {
char[] buf = new char[1024];
for(int numRead = 0; (numRead = reader.read(buf)) != -1; buf = new char[1024]) {
fileData.append(String.valueOf(buf, 0, numRead));
}
} finally {
reader.close();
}
return fileData.toString();
}