Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unittest for paramiko ssh connection

I wrote some python code that works great, now I'm tasked with writing tests for that code. My team uses mock and pytest, but I haven't really been able to copy-paste and modify something useful. I just need a kick start, for example here is a part of my code:

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname='1.2.3.4', username='ubuntu')

Can someone help me write a simple unittest for this? I understand that going forward I'd have to think about my code and write the tests as I go, but I've never done this before so I'm really just looking to get a practical start to get going.

like image 285
Naim Salameh Avatar asked Jun 03 '26 05:06

Naim Salameh


1 Answers

Unit testing ensures the code works per requirements. Get the requirements and write tests to check that the code works and show that the code throws appropriate errors. You can use RobotFramework or another test automation SW to automate the tests. Some questions you might ask yourself are listed below:

ssh = paramiko.SSHClient()

  • Does paramiko.SSHClient exist?
  • is it working?
  • what if it fails?
  • do you get an error or does the SW hang?

ssh.load_system_host_keys()

  • Can you load the system keys?
  • How can you verify this?

ssh.connect(hostname='1.2.3.4', username='ubuntu')

  • How can you prove the connection exists?
  • What happens if you try to connect to another host?
  • Do you get an error message?
  • Can you logon with username 'ubuntu'?
  • What if you try another username?
  • Does the connection fail?
  • Do you get a generic error so you don't give crackers clues about your security?

Proof of unit testing is usually a screen capture, log entry, or some documentation showing you got the result you expected when you ran the test. Hope this helps.

like image 161
Nelson Stacy Avatar answered Jun 06 '26 05:06

Nelson Stacy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!