File: test_model_component_evidence.py

package info (click to toggle)
cyclonedx-python-lib 11.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,044 kB
  • sloc: xml: 20,462; python: 12,968; makefile: 21; sh: 16
file content (257 lines) | stat: -rw-r--r-- 10,631 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# This file is part of CycloneDX Python Library
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) OWASP Foundation. All Rights Reserved.

from decimal import Decimal
from unittest import TestCase

from cyclonedx.exception.model import InvalidConfidenceException
from cyclonedx.model import Copyright
from cyclonedx.model.component_evidence import (
    AnalysisTechnique,
    CallStack,
    CallStackFrame,
    ComponentEvidence,
    Identity,
    IdentityField,
    Method,
    Occurrence,
)


class TestModelComponentEvidence(TestCase):

    def test_no_params(self) -> None:
        ComponentEvidence()  # Does not raise `NoPropertiesProvidedException`

    def test_identity_single(self) -> None:
        identity = Identity(field=IdentityField.NAME, confidence=Decimal('1'), concluded_value='test')
        ce = ComponentEvidence(identity=identity)
        self.assertEqual(len(ce.identity), 1)
        self.assertEqual(ce.identity.pop().field, 'name')

    def test_identity_multiple(self) -> None:
        identities = [
            Identity(field=IdentityField.NAME, confidence=Decimal('1'), concluded_value='test'),
            Identity(field=IdentityField.VERSION, confidence=Decimal('0.8'), concluded_value='1.0.0')
        ]
        ce = ComponentEvidence(identity=identities)
        self.assertEqual(len(ce.identity), 2)

    def test_identity_with_methods(self) -> None:
        """Test identity with analysis methods"""
        methods = [
            Method(
                technique=AnalysisTechnique.BINARY_ANALYSIS,  # Changed order to test sorting
                confidence=Decimal('0.9'),
                value='Found in binary'
            ),
            Method(
                technique=AnalysisTechnique.SOURCE_CODE_ANALYSIS,
                confidence=Decimal('0.8'),
                value='Found in source'
            )
        ]
        identity = Identity(field='name', confidence=Decimal('1'), methods=methods)
        self.assertEqual(len(identity.methods), 2)
        sorted_methods = sorted(methods)  # Methods should be sorted by technique name
        self.assertEqual(list(identity.methods), sorted_methods)

        # Verify first method
        method = sorted_methods[0]
        self.assertEqual(method.technique, AnalysisTechnique.BINARY_ANALYSIS)
        self.assertEqual(method.confidence, Decimal('0.9'))
        self.assertEqual(method.value, 'Found in binary')

    def test_method_sorting(self) -> None:
        """Test that methods are properly sorted by technique value"""
        methods = [
            Method(technique=AnalysisTechnique.SOURCE_CODE_ANALYSIS, confidence=Decimal('0.8')),
            Method(technique=AnalysisTechnique.BINARY_ANALYSIS, confidence=Decimal('0.9')),
            Method(technique=AnalysisTechnique.ATTESTATION, confidence=Decimal('1.0'))
        ]

        sorted_methods = sorted(methods)
        self.assertEqual(sorted_methods[0].technique, AnalysisTechnique.ATTESTATION)
        self.assertEqual(sorted_methods[1].technique, AnalysisTechnique.BINARY_ANALYSIS)
        self.assertEqual(sorted_methods[2].technique, AnalysisTechnique.SOURCE_CODE_ANALYSIS)

    def test_invalid_method_confidence(self) -> None:
        """Test that invalid confidence raises ValueError"""
        with self.assertRaises(InvalidConfidenceException):
            Method(technique=AnalysisTechnique.FILENAME, confidence=Decimal('1.5'))

    def test_occurrences(self) -> None:
        occurrence = Occurrence(location='/path/to/file', line=42)
        ce = ComponentEvidence(occurrences=[occurrence])
        self.assertEqual(len(ce.occurrences), 1)
        self.assertEqual(ce.occurrences.pop().line, 42)

    def test_callstack(self) -> None:
        frame = CallStackFrame(
            package='com.example',
            module='app',
            function='main'
        )
        stack = CallStack(frames=[frame])
        ce = ComponentEvidence(callstack=stack)
        self.assertIsNotNone(ce.callstack)
        self.assertEqual(len(ce.callstack.frames), 1)

    def test_licenses(self) -> None:
        from cyclonedx.model.license import DisjunctiveLicense
        license = DisjunctiveLicense(id='MIT')
        ce = ComponentEvidence(licenses=[license])
        self.assertEqual(len(ce.licenses), 1)

    def test_copyright(self) -> None:
        copyright = Copyright(text='(c) 2023')
        ce = ComponentEvidence(copyright=[copyright])
        self.assertEqual(len(ce.copyright), 1)
        self.assertEqual(ce.copyright.pop().text, '(c) 2023')

    def test_full_evidence(self) -> None:
        # Test with all fields populated
        identity = Identity(field=IdentityField.NAME, confidence=Decimal('1'), concluded_value='test')
        occurrence = Occurrence(location='/path/to/file', line=42)
        frame = CallStackFrame(module='app', function='main', line=1)
        stack = CallStack(frames=[frame])
        from cyclonedx.model.license import DisjunctiveLicense
        license = DisjunctiveLicense(id='MIT')
        copyright = Copyright(text='(c) 2023')

        ce = ComponentEvidence(
            identity=[identity],
            occurrences=[occurrence],
            callstack=stack,
            licenses=[license],
            copyright=[copyright]
        )

        self.assertEqual(len(ce.identity), 1)
        self.assertEqual(len(ce.occurrences), 1)
        self.assertIsNotNone(ce.callstack)
        self.assertEqual(len(ce.callstack.frames), 1)
        self.assertEqual(len(ce.licenses), 1)
        self.assertEqual(len(ce.copyright), 1)

    def test_full_evidence_with_complete_stack(self) -> None:
        identity = Identity(field=IdentityField.NAME, confidence=Decimal('1'), concluded_value='test')
        occurrence = Occurrence(location='/path/to/file', line=42)

        frame = CallStackFrame(
            package='com.example',
            module='app',
            function='main',
            parameters=['arg1', 'arg2'],
            line=1,
            column=10,
            full_filename='/path/to/file.py'
        )
        stack = CallStack(frames=[frame])

        from cyclonedx.model.license import DisjunctiveLicense
        license = DisjunctiveLicense(id='MIT')
        copyright = Copyright(text='(c) 2023')

        ce = ComponentEvidence(
            identity=[identity],
            occurrences=[occurrence],
            callstack=stack,
            licenses=[license],
            copyright=[copyright]
        )

        self.assertEqual(len(ce.identity), 1)
        self.assertEqual(len(ce.occurrences), 1)
        self.assertIsNotNone(ce.callstack)
        self.assertEqual(len(ce.callstack.frames), 1)
        self.assertEqual(ce.callstack.frames.pop().package, 'com.example')
        self.assertEqual(len(ce.licenses), 1)
        self.assertEqual(len(ce.copyright), 1)

    def test_same_1(self) -> None:
        ce_1 = ComponentEvidence(copyright=[Copyright(text='Commercial')])
        ce_2 = ComponentEvidence(copyright=[Copyright(text='Commercial')])
        self.assertEqual(hash(ce_1), hash(ce_2))
        self.assertTrue(ce_1 == ce_2)

    def test_same_2(self) -> None:
        ce_1 = ComponentEvidence(copyright=[Copyright(text='Commercial'), Copyright(text='Commercial 2')])
        ce_2 = ComponentEvidence(copyright=[Copyright(text='Commercial 2'), Copyright(text='Commercial')])
        self.assertEqual(hash(ce_1), hash(ce_2))
        self.assertTrue(ce_1 == ce_2)

    def test_not_same_1(self) -> None:
        ce_1 = ComponentEvidence(copyright=[Copyright(text='Commercial')])
        ce_2 = ComponentEvidence(copyright=[Copyright(text='Commercial 2')])
        self.assertNotEqual(hash(ce_1), hash(ce_2))
        self.assertFalse(ce_1 == ce_2)

    def test_component_evidence_sorting(self) -> None:
        """Test that ComponentEvidence instances can be sorted without triggering TypeError"""
        ce_1 = ComponentEvidence(copyright=[Copyright(text='Copyright A')])
        ce_2 = ComponentEvidence(copyright=[Copyright(text='Copyright B')])
        ce_3 = ComponentEvidence(copyright=[Copyright(text='Copyright C')])

        # This should not raise TypeError: '<' not supported between instances
        evidence_list = [ce_3, ce_1, ce_2]
        sorted_evidence = sorted(evidence_list)
        self.assertEqual(len(sorted_evidence), 3)


class TestModelCallStackFrame(TestCase):

    def test_fields(self) -> None:
        # Test CallStackFrame with required fields
        frame = CallStackFrame(
            package='com.example',
            module='app',
            function='main',
            parameters=['arg1', 'arg2'],
            line=1,
            column=10,
            full_filename='/path/to/file.py'
        )
        self.assertEqual(frame.package, 'com.example')
        self.assertEqual(frame.module, 'app')
        self.assertEqual(frame.function, 'main')
        self.assertEqual(len(frame.parameters), 2)
        self.assertEqual(frame.line, 1)
        self.assertEqual(frame.column, 10)
        self.assertEqual(frame.full_filename, '/path/to/file.py')

    def test_module_required(self) -> None:
        """Test that module is the only required field"""
        frame = CallStackFrame(module='app')  # Only mandatory field
        self.assertEqual(frame.module, 'app')
        self.assertIsNone(frame.package)
        self.assertIsNone(frame.function)
        self.assertEqual(len(frame.parameters), 0)
        self.assertIsNone(frame.line)
        self.assertIsNone(frame.column)
        self.assertIsNone(frame.full_filename)

    def test_callstack_frame_sorting(self) -> None:
        """Test that CallStackFrame instances can be sorted without triggering TypeError"""
        frame1 = CallStackFrame(module='app_a', function='func_a')
        frame2 = CallStackFrame(module='app_b', function='func_b')
        frame3 = CallStackFrame(module='app_c', function='func_c')

        # This should not raise TypeError: '<' not supported between instances
        frame_list = [frame3, frame1, frame2]
        sorted_frames = sorted(frame_list)
        self.assertEqual(len(sorted_frames), 3)