Initial import to Tizen
[profile/ivi/python-twisted.git] / twisted / conch / test / test_ckeygen.py
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 Tests for L{twisted.conch.scripts.ckeygen}.
6 """
7
8 import sys
9 from StringIO import StringIO
10
11 try:
12     import Crypto
13     import pyasn1
14 except ImportError:
15     skip = "PyCrypto and pyasn1 required for twisted.conch.scripts.ckeygen."
16 else:
17     from twisted.conch.ssh.keys import Key
18     from twisted.conch.scripts.ckeygen import printFingerprint, _saveKey
19
20 from twisted.python.filepath import FilePath
21 from twisted.trial.unittest import TestCase
22 from twisted.conch.test.keydata import publicRSA_openssh, privateRSA_openssh
23
24
25
26 class KeyGenTests(TestCase):
27     """
28     Tests for various functions used to implement the I{ckeygen} script.
29     """
30     def setUp(self):
31         """
32         Patch C{sys.stdout} with a L{StringIO} instance to tests can make
33         assertions about what's printed.
34         """
35         self.stdout = StringIO()
36         self.patch(sys, 'stdout', self.stdout)
37
38
39     def test_printFingerprint(self):
40         """
41         L{printFingerprint} writes a line to standard out giving the number of
42         bits of the key, its fingerprint, and the basename of the file from it
43         was read.
44         """
45         filename = self.mktemp()
46         FilePath(filename).setContent(publicRSA_openssh)
47         printFingerprint({'filename': filename})
48         self.assertEqual(
49             self.stdout.getvalue(),
50             '768 3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af temp\n')
51
52
53     def test_saveKey(self):
54         """
55         L{_saveKey} writes the private and public parts of a key to two
56         different files and writes a report of this to standard out.
57         """
58         base = FilePath(self.mktemp())
59         base.makedirs()
60         filename = base.child('id_rsa').path
61         key = Key.fromString(privateRSA_openssh)
62         _saveKey(
63             key.keyObject,
64             {'filename': filename, 'pass': 'passphrase'})
65         self.assertEqual(
66             self.stdout.getvalue(),
67             "Your identification has been saved in %s\n"
68             "Your public key has been saved in %s.pub\n"
69             "The key fingerprint is:\n"
70             "3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af\n" % (
71                 filename,
72                 filename))
73         self.assertEqual(
74             key.fromString(
75                 base.child('id_rsa').getContent(), None, 'passphrase'),
76             key)
77         self.assertEqual(
78             Key.fromString(base.child('id_rsa.pub').getContent()),
79             key.public())
80