rpcauth-test.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2015-2018 The Limenka developers
   3  # Distributed under the MIT software license, see the accompanying
   4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  """Test share/rpcauth/rpcauth.py
   6  """
   7  import re
   8  import configparser
   9  import hmac
  10  import importlib
  11  import os
  12  import sys
  13  import unittest
  14  
  15  class TestRPCAuth(unittest.TestCase):
  16      def setUp(self):
  17          config = configparser.ConfigParser()
  18          config_path = os.path.abspath(
  19              os.path.join(os.sep, os.path.abspath(os.path.dirname(__file__)),
  20              "../config.ini"))
  21          with open(config_path, encoding="utf8") as config_file:
  22              config.read_file(config_file)
  23          sys.path.insert(0, os.path.dirname(config['environment']['RPCAUTH']))
  24          self.rpcauth = importlib.import_module('rpcauth')
  25  
  26      def test_generate_salt(self):
  27          for i in range(16, 32 + 1):
  28              self.assertEqual(len(self.rpcauth.generate_salt(i)), i * 2)
  29  
  30      def test_generate_password(self):
  31          """Test that generated passwords only consist of urlsafe characters."""
  32          r = re.compile(r"[0-9a-zA-Z_-]*")
  33          password = self.rpcauth.generate_password()
  34          self.assertTrue(r.fullmatch(password))
  35  
  36      def test_check_password_hmac(self):
  37          salt = self.rpcauth.generate_salt(16)
  38          password = self.rpcauth.generate_password()
  39          password_hmac = self.rpcauth.password_to_hmac(salt, password)
  40  
  41          m = hmac.new(salt.encode('utf-8'), password.encode('utf-8'), 'SHA256')
  42          expected_password_hmac = m.hexdigest()
  43  
  44          self.assertEqual(expected_password_hmac, password_hmac)
  45  
  46  if __name__ == '__main__':
  47      unittest.main()
  48