1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4#
5# Copyright 2017, Data61
6# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
7# ABN 41 687 119 230.
8#
9# This software may be distributed and modified according to the terms of
10# the BSD 2-Clause license. Note that NO WARRANTY is provided.
11# See "LICENSE_BSD2.txt" for details.
12#
13# @TAG(DATA61_BSD)
14#
15
16from __future__ import absolute_import, division, print_function, \
17    unicode_literals
18
19import codecs, os, subprocess, sys, unittest
20
21ME = os.path.abspath(__file__)
22
23# Make CAmkES importable
24sys.path.append(os.path.join(os.path.dirname(ME), '../../..'))
25
26from camkes.internal.strhash import hash_string
27from camkes.internal.tests.utils import CAmkESTest, sha256sum_available, which
28
29class TestStringHash(CAmkESTest):
30    def sha256(self, data):
31        assert which('sha256sum') is not None
32        tmp = self.mkstemp()
33        with codecs.open(tmp, 'w', 'utf-8') as f:
34            f.write(data)
35        sha = subprocess.check_output(['sha256sum', tmp],
36            universal_newlines=True).split(' ')[0]
37        return sha
38
39    @unittest.skipIf(not sha256sum_available(), 'sha256sum not found')
40    def test_hash_empty(self):
41        sha1 = self.sha256('')
42        sha2 = hash_string('')
43
44        self.assertEqual(sha1, sha2)
45
46    @unittest.skipIf(not sha256sum_available(), 'sha256sum not found')
47    def test_hash_basic(self):
48        sha1 = self.sha256('hello world')
49        sha2 = hash_string('hello world')
50
51        self.assertEqual(sha1, sha2)
52
53    @unittest.skipIf(not sha256sum_available(), 'sha256sum not found')
54    def test_strange_bytes(self):
55        sha1 = self.sha256('hello \x43world')
56        sha2 = hash_string('hello \x43world')
57
58        self.assertEqual(sha1, sha2)
59
60if __name__ == '__main__':
61    unittest.main()
62