|
1 |
| -package tests |
| 1 | +package scp |
2 | 2 |
|
3 | 3 | import (
|
4 | 4 | "context"
|
@@ -317,3 +317,75 @@ func TestFileNotFound(t *testing.T) {
|
317 | 317 | t.Errorf("Expected %v, got %v", expected, err.Error())
|
318 | 318 | }
|
319 | 319 | }
|
| 320 | + |
| 321 | +func TestUserSuppliedSSHClientDoesNotClose(t *testing.T) { |
| 322 | + // create the SSH connection |
| 323 | + clientConfig, err := buildClientConfig() |
| 324 | + if err != nil { |
| 325 | + t.Error("Could not build client config", clientConfig) |
| 326 | + } |
| 327 | + |
| 328 | + sshClient, err := ssh.Dial("tcp", "127.0.0.1:2244", &clientConfig) |
| 329 | + if err != nil { |
| 330 | + t.Error("Could not establish SSH connection", err) |
| 331 | + } |
| 332 | + defer sshClient.Close() |
| 333 | + |
| 334 | + // create the SCP client |
| 335 | + client, err := scp.NewClientBySSH(sshClient) |
| 336 | + if err != nil { |
| 337 | + t.Error("Could not create SCP client", err) |
| 338 | + } |
| 339 | + |
| 340 | + // copy a file for good measure |
| 341 | + |
| 342 | + f, _ := os.Open("./data/upload_file.txt") |
| 343 | + defer f.Close() |
| 344 | + |
| 345 | + err = client.CopyFile(context.Background(), f, "/data/test.txt", "0777") |
| 346 | + |
| 347 | + if err != nil { |
| 348 | + t.Error("Could not copy file to remote", err) |
| 349 | + } |
| 350 | + |
| 351 | + // then close the SCP client |
| 352 | + client.Close() |
| 353 | + |
| 354 | + var session *ssh.Session |
| 355 | + |
| 356 | + // ensure that the SSH client is still opened |
| 357 | + // we do so by creating a new session, if this fails |
| 358 | + // the SSH connection was already closed |
| 359 | + if session, err = sshClient.NewSession(); err != nil { |
| 360 | + t.Fatal("SSH session was already closed.") |
| 361 | + } |
| 362 | + |
| 363 | + session.Close() |
| 364 | +} |
| 365 | + |
| 366 | +// Ensure that the underlying SSH client managed by the library is correctly closed |
| 367 | +// after closing the SCP connection |
| 368 | +func TestSSHClientNoLeak(t *testing.T) { |
| 369 | + client := establishConnection(t) |
| 370 | + |
| 371 | + // copy a file for good measure |
| 372 | + f, _ := os.Open("./data/upload_file.txt") |
| 373 | + defer f.Close() |
| 374 | + |
| 375 | + err := client.CopyFile(context.Background(), f, "/data/test.txt", "0777") |
| 376 | + |
| 377 | + if err != nil { |
| 378 | + t.Error("Could not copy file to remote", err) |
| 379 | + } |
| 380 | + |
| 381 | + // then close the SCP client |
| 382 | + client.Close() |
| 383 | + |
| 384 | + // ensure that the SSH client is still opened |
| 385 | + // we do so by creating a new session, if this fails |
| 386 | + // the SSH connection was already closed |
| 387 | + if session, err := client.SSHClient().NewSession(); err == nil { |
| 388 | + session.Close() |
| 389 | + t.Fatal("SSH session was not closed.") |
| 390 | + } |
| 391 | +} |
0 commit comments