juice-shop

Форк
0
/
code-snippet.component.spec.ts 
209 строк · 7.9 Кб
1
/*
2
 * Copyright (c) 2014-2024 Bjoern Kimminich & the OWASP Juice Shop contributors.
3
 * SPDX-License-Identifier: MIT
4
 */
5

6
import { TranslateModule } from '@ngx-translate/core'
7
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'
8
import { HttpClientTestingModule } from '@angular/common/http/testing'
9
import { MatDividerModule } from '@angular/material/divider'
10
import { type ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'
11

12
import { CodeSnippetComponent } from './code-snippet.component'
13
import { CodeSnippetService } from '../Services/code-snippet.service'
14
import { CookieModule, CookieService } from 'ngx-cookie'
15
import { ConfigurationService } from '../Services/configuration.service'
16
import { of, throwError } from 'rxjs'
17
import { CodeFixesService } from '../Services/code-fixes.service'
18
import { VulnLinesService } from '../Services/vuln-lines.service'
19
import { ChallengeService } from '../Services/challenge.service'
20

21
describe('CodeSnippetComponent', () => {
22
  let component: CodeSnippetComponent
23
  let fixture: ComponentFixture<CodeSnippetComponent>
24
  let configurationService: any
25
  let cookieService: any
26
  let codeSnippetService: any
27
  let codeFixesService: any
28
  let vulnLinesService: any
29
  let challengeService: any
30

31
  beforeEach(waitForAsync(() => {
32
    configurationService = jasmine.createSpyObj('ConfigurationService', ['getApplicationConfiguration'])
33
    configurationService.getApplicationConfiguration.and.returnValue(of({ application: {}, challenges: {} }))
34
    cookieService = jasmine.createSpyObj('CookieService', ['put'])
35
    codeSnippetService = jasmine.createSpyObj('CodeSnippetService', ['get', 'check'])
36
    codeSnippetService.get.and.returnValue(of({}))
37
    codeFixesService = jasmine.createSpyObj('CodeFixesService', ['get', 'check'])
38
    codeFixesService.get.and.returnValue(of({}))
39
    vulnLinesService = jasmine.createSpyObj('VulnLinesService', ['check'])
40
    challengeService = jasmine.createSpyObj('ChallengeService', ['continueCodeFindIt', 'continueCodeFixIt'])
41
    challengeService.continueCodeFindIt.and.returnValue(of('continueCodeFindIt'))
42
    challengeService.continueCodeFixIt.and.returnValue(of('continueCodeFixIt'))
43

44
    TestBed.configureTestingModule({
45
      imports: [
46
        CookieModule.forRoot(),
47
        TranslateModule.forRoot(),
48
        HttpClientTestingModule,
49
        MatDividerModule,
50
        MatDialogModule
51
      ],
52
      declarations: [CodeSnippetComponent],
53
      providers: [
54
        { provide: MatDialogRef, useValue: {} },
55
        { provide: MAT_DIALOG_DATA, useValue: { dialogData: {} } },
56
        { provide: ConfigurationService, useValue: configurationService },
57
        { provide: CookieService, useValue: cookieService },
58
        { provide: CodeSnippetService, useValue: codeSnippetService },
59
        { provide: CodeFixesService, useValue: codeFixesService },
60
        { provide: VulnLinesService, useValue: vulnLinesService },
61
        { provide: ChallengeService, useValue: challengeService }
62
      ]
63
    })
64
      .compileComponents()
65
  }))
66

67
  beforeEach(() => {
68
    fixture = TestBed.createComponent(CodeSnippetComponent)
69
    component = fixture.componentInstance
70
    fixture.detectChanges()
71
  })
72

73
  it('should create', () => {
74
    expect(component).toBeTruthy()
75
  })
76

77
  it('should log the error on retrieving configuration', () => {
78
    configurationService.getApplicationConfiguration.and.returnValue(throwError('Error'))
79
    console.log = jasmine.createSpy('log')
80
    component.ngOnInit()
81
    expect(console.log).toHaveBeenCalledWith('Error')
82
  })
83

84
  it('should set the retrieved snippet', () => {
85
    codeSnippetService.get.and.returnValue(of({ snippet: 'Snippet' }))
86
    component.ngOnInit()
87
    expect(component.snippet).toEqual({ snippet: 'Snippet' })
88
  })
89

90
  it('Default status and icons should reflect both challenge phases yet unsolved', () => {
91
    component.ngOnInit()
92
    expect(component.result).toBe(0)
93
    expect(component.lock).toBe(0)
94
    expect(component.solved.findIt).toBeFalse()
95
  })
96

97
  it('should set status and icons for solved "Find It" phase', () => {
98
    component.dialogData.codingChallengeStatus = 1
99
    component.ngOnInit()
100
    expect(component.result).toBe(1)
101
    expect(component.lock).toBe(1)
102
    expect(component.solved.findIt).toBeTrue()
103
  })
104

105
  it('should set an error on snippet retrieval as the snippet', () => {
106
    codeSnippetService.get.and.returnValue(throwError({ error: 'Error' }))
107
    component.ngOnInit()
108
    expect(component.snippet).toEqual({ snippet: 'Error' })
109
  })
110

111
  it('should set empty fixes on error during fixes retrieval', () => {
112
    codeFixesService.get.and.returnValue(throwError('Error'))
113
    component.ngOnInit()
114
    expect(component.fixes).toBeNull()
115
  })
116

117
  it('selected code lines are set in component', () => {
118
    component.selectedLines = [42]
119
    component.addLine([1, 3, 5])
120
    expect(component.selectedLines).toEqual([1, 3, 5])
121
  })
122

123
  it('selected code fix is set in component', () => {
124
    component.selectedFix = 42
125
    component.setFix(1)
126
    expect(component.selectedFix).toBe(1)
127
  })
128

129
  it('selecting a code fix clears previous explanation', () => {
130
    component.explanation = 'Wrong answer!'
131
    component.setFix(1)
132
    expect(component.explanation).toBeNull()
133
  })
134

135
  it('lock icon is red and "locked" when no fixes are available', () => {
136
    component.fixes = null
137
    expect(component.lockIcon()).toBe('lock')
138
    expect(component.lockColor()).toBe('warn')
139
  })
140

141
  it('lock icon is red and "locked" by default', () => {
142
    component.fixes = ['Fix1', 'Fix2', 'Fix3']
143
    component.lock = 0
144
    expect(component.lockIcon()).toBe('lock')
145
    expect(component.lockColor()).toBe('warn')
146
  })
147

148
  it('lock icon is red and "locked" when "Find It" phase is unsolved', () => {
149
    component.fixes = ['Fix1', 'Fix2', 'Fix3']
150
    component.lock = 2
151
    expect(component.lockIcon()).toBe('lock')
152
    expect(component.lockColor()).toBe('warn')
153
  })
154

155
  it('lock icon is green and "lock_open" when "Find It" phase is in solved', () => {
156
    component.fixes = ['Fix1', 'Fix2', 'Fix3']
157
    component.lock = 1
158
    expect(component.lockIcon()).toBe('lock_open')
159
    expect(component.lockColor()).toBe('accent')
160
  })
161

162
  it('result icon is "send" when choice is not yet submitted', () => {
163
    component.result = 0
164
    expect(component.resultIcon()).toBe('send')
165
  })
166

167
  it('result icon is red "clear" when wrong answer has been submitted', () => {
168
    component.result = 2
169
    expect(component.resultIcon()).toBe('clear')
170
    expect(component.resultColor()).toBe('warn')
171
  })
172

173
  it('result icon is green "check" when right answer has been submitted', () => {
174
    component.result = 1
175
    expect(component.resultIcon()).toBe('check')
176
    expect(component.resultColor()).toBe('accent')
177
  })
178

179
  it('correctly submitted vulnerable lines toggle positive verdict for "Find It" phase', () => {
180
    component.tab.setValue(0)
181
    vulnLinesService.check.and.returnValue(of({ verdict: true }))
182
    component.checkLines()
183
    expect(component.solved.findIt).toBeTrue()
184
  })
185

186
  xit('correctly submitted vulnerable lines toggle tab to "Fix It" if code fixes exist', waitForAsync(() => {
187
    component.tab.setValue(0)
188
    component.fixes = ['Fix1', 'Fix2', 'Fix3']
189
    vulnLinesService.check.and.returnValue(of({ verdict: true }))
190
    component.checkLines()
191
    expect(component.tab.value).toBe(1)
192
  }))
193

194
  it('correctly submitted fix toggles positive verdict for "Fix It" phase', () => {
195
    component.tab.setValue(1)
196
    component.randomFixes = [{ fix: 'Fix 1', index: 0 }]
197
    codeFixesService.check.and.returnValue(of({ verdict: true }))
198
    component.checkFix()
199
    expect(component.solved.fixIt).toBeTrue()
200
  })
201

202
  it('should remember the original order of available code fix options when shuffling', () => {
203
    component.fixes = ['Fix 1', 'Fix 2', 'Fix 3']
204
    component.shuffle()
205
    expect(component.randomFixes).toContain({ fix: 'Fix 1', index: 0 })
206
    expect(component.randomFixes).toContain({ fix: 'Fix 2', index: 1 })
207
    expect(component.randomFixes).toContain({ fix: 'Fix 3', index: 2 })
208
  })
209
})
210

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.