Elffuss BraidHub

kikocis/continue public

main · 12.2 KiBRawPermalink
1import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply";
2
3describe("isUnifiedDiffFormat", () => {
4 it("should return true for valid unified diff format", () => {
5 const validDiff = `--- original.txt
6+++ modified.txt
7@@ -1,3 +1,4 @@
8 line1
9-line2
10+newline2
11+newline3
12 line3`;
13 expect(isUnifiedDiffFormat(validDiff)).toBe(true);
14 });
15
16 it("should return false for empty diff", () => {
17 expect(isUnifiedDiffFormat("")).toBe(false);
18 });
19
20 it("should return false for diff without hunk header", () => {
21 const invalidDiff = `--- original.txt
22+++ modified.txt
23+line1
24-line2
25+line3`;
26 expect(isUnifiedDiffFormat(invalidDiff)).toBe(false);
27 });
28
29 it("should return false for diff without valid content", () => {
30 const invalidDiff = `--- original.txt
31+++ modified.txt
32@@ -1,3 +1,4 @@`;
33 expect(isUnifiedDiffFormat(invalidDiff)).toBe(false);
34 });
35
36 it("should return true even without file headers if hunk headers exist", () => {
37 const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
38 line1
39-line2
40+newline2
41+newline3
42 line3`;
43 expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
44 });
45
46 it("should return true in case of empty lines", () => {
47 const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
48 line1
49
50-line2
51+newline2
52
53 line3`;
54 expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
55 });
56});
57
58describe("applyUnifiedDiff", () => {
59 it("should correctly apply a add line of unified diff", () => {
60 const sourceCode = `func main() {
61 scanner := bufio.NewScanner(os.Stdin)
62 fmt.Println("Calculator started! Available operations:")
63 fmt.Println(" + : Addition")
64 fmt.Println(" - : Subtraction")
65 fmt.Println(" * : Multiplication")
66 fmt.Println(" / : Division")
67 fmt.Println(" ^ : Power")
68 fmt.Println(" √ : Square root (use only one number)")
69}
70// End of file`;
71
72 const diffText = `--- original.go
73+++ updated.go
74@@ -30,6 +30,7 @@
75 fmt.Println(" / : Division")
76 fmt.Println(" ^ : Power")
77 fmt.Println(" √ : Square root (use only one number)")
78+ fmt.Println(" log: Logarithm (use 'log base number')")
79 }`;
80
81 const result = applyUnifiedDiff(sourceCode, diffText);
82
83 const expected = [
84 { type: "same", line: "func main() {" },
85 { type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" },
86 {
87 type: "same",
88 line: ' fmt.Println("Calculator started! Available operations:")',
89 },
90 { type: "same", line: ' fmt.Println(" + : Addition")' },
91 { type: "same", line: ' fmt.Println(" - : Subtraction")' },
92 { type: "same", line: ' fmt.Println(" * : Multiplication")' },
93 { type: "same", line: ' fmt.Println(" / : Division")' },
94 { type: "same", line: ' fmt.Println(" ^ : Power")' },
95 {
96 type: "same",
97 line: ' fmt.Println(" √ : Square root (use only one number)")',
98 },
99 {
100 type: "new",
101 line: " fmt.Println(\" log: Logarithm (use 'log base number')\")",
102 },
103 { type: "same", line: "}" },
104 { type: "same", line: "// End of file" },
105 ];
106
107 expect(result).toEqual(expected);
108 });
109
110 it("should correctly apply multiple insertions and deletions", () => {
111 const sourceCode = `package main
112
113import "fmt"
114
115func main() {
116 fmt.Println("Hello")
117 fmt.Println("World")
118}`;
119
120 const diffText = `--- original.go
121+++ updated.go
122@@ -1,8 +1,11 @@
123 package main
124
125-import "fmt"
126+import (
127+ "fmt"
128+ "time"
129+)
130
131 func main() {
132- fmt.Println("Hello")
133+ fmt.Printf("The time is: %v\\n", time.Now())
134- fmt.Println("World")
135+ fmt.Println("Goodbye!")
136 }`;
137 const result = applyUnifiedDiff(sourceCode, diffText);
138
139 const expected = [
140 { type: "same", line: "package main" },
141 { type: "same", line: "" },
142 { type: "old", line: 'import "fmt"' },
143 { type: "new", line: "import (" },
144 { type: "new", line: ' "fmt"' },
145 { type: "new", line: ' "time"' },
146 { type: "new", line: ")" },
147 { type: "same", line: "" },
148 { type: "same", line: "func main() {" },
149 { type: "old", line: ' fmt.Println("Hello")' },
150 { type: "new", line: ' fmt.Printf("The time is: %v\\n", time.Now())' },
151 { type: "old", line: ' fmt.Println("World")' },
152 { type: "new", line: ' fmt.Println("Goodbye!")' },
153 { type: "same", line: "}" },
154 ];
155
156 expect(result).toEqual(expected);
157 });
158
159 it("should correctly apply multiple diff blocks", () => {
160 const sourceCode = `package main
161import (
162 "bufio"
163 "fmt"
164 "math"
165 "os"
166 "strconv"
167 "strings"
168 "testing"
169)
170func main() {
171 scanner := bufio.NewScanner(os.Stdin)
172 fmt.Println("Calculator started! Available operations:")
173 fmt.Println(" + : Addition")
174 fmt.Println(" - : Subtraction")
175 fmt.Println(" * : Multiplication")
176 fmt.Println(" / : Division")
177 fmt.Println(" ^ : Power")
178 fmt.Println(" √ : Square root (use only one number)")
179 for {
180 fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ")
181 scanner.Scan()
182 input := scanner.Text()
183 if strings.ToLower(input) == "q" {
184 fmt.Println("Goodbye!")
185 break
186 }
187 result, err := calculate(input)
188 if err != nil {
189 fmt.Printf("Error: %v\n", err)
190 continue
191 }
192 fmt.Printf("Result: %v\n", result)
193 }
194}
195func calculate(input string) (float64, error) {
196 parts := strings.Fields(input)
197 if len(parts) < 2 {
198 return 0, fmt.Errorf("invalid input format: please use 'number operator number' or '√ number'")
199 }
200 if parts[0] == "√" {
201 if len(parts) != 2 {
202 return 0, fmt.Errorf("square root operation requires exactly one number")
203 }
204 num, err := strconv.ParseFloat(parts[1], 64)
205 if err != nil {
206 return 0, fmt.Errorf("invalid number for square root: %v", err)
207 }
208 if num < 0 {
209 return 0, fmt.Errorf("cannot calculate square root of a negative number")
210 }
211 return math.Sqrt(num), nil
212 }
213 if len(parts) != 3 {
214 return 0, fmt.Errorf("invalid input format: please use 'number operator number'")
215 }
216 num1, err := strconv.ParseFloat(parts[0], 64)
217 if err != nil {
218 return 0, fmt.Errorf("invalid first number: %v", err)
219 }
220 operator := parts[1]
221 num2, err := strconv.ParseFloat(parts[2], 64)
222 if err != nil {
223 return 0, fmt.Errorf("invalid second number: %v", err)
224 }
225 switch operator {
226 case "+":
227 return num1 + num2, nil
228 case "-":
229 return num1 - num2, nil
230 case "*":
231 return num1 * num2, nil
232 case "/":
233 if num2 == 0 {
234 return 0, fmt.Errorf("division by zero is not allowed")
235 }
236 return num1 / num2, nil
237 case "^":
238 return math.Pow(num1, num2), nil
239 default:
240 return 0, fmt.Errorf("invalid operator: must be +, -, *, /, ^, or √")
241 }
242}
243func TestCalculate(t *testing.T) {
244 tests := []struct {
245 input string
246 expected float64
247 hasError bool
248 }{
249 {"2 + 3", 5, false},
250 {"10 - 5", 5, false},
251 {"4 * 3", 12, false},
252 {"15 / 3", 5, false},
253 {"2 ^ 3", 8, false},
254 {"√ 16", 4, false},
255 {"2 + a", 0, true},
256 {"15 / 0", 0, true},
257 {"√ -4", 0, true},
258 {"3 $ 4", 0, true},
259 {"", 0, true},
260 {"1", 0, true},
261 {"1 +", 0, true},
262 {"+ 1", 0, true},
263 {"√ 2 3", 0, true},
264 }
265 for _, test := range tests {
266 result, err := calculate(test.input)
267 if test.hasError && err == nil {
268 t.Errorf("Expected error for input '%s', but got none", test.input)
269 continue
270 }
271 if !test.hasError && err != nil {
272 t.Errorf("Unexpected error for input '%s': %v", test.input, err)
273 continue
274 }
275 if !test.hasError && result != test.expected {
276 t.Errorf("For input '%s': expected %f, but got %f", test.input, test.expected, result)
277 }
278 }
279}
280func TestSpecialCases(t *testing.T) {
281 result, err := calculate("2.5 + 2.5")
282 if err != nil {
283 t.Errorf("Unexpected error for floating point addition: %v", err)
284 }
285 if result != 5.0 {
286 t.Errorf("Floating point addition failed: expected 5.0, got %f", result)
287 }
288 result, err = calculate("2.5 ^ 2")
289 if err != nil {
290 t.Errorf("Unexpected error for power operation: %v", err)
291 }
292 expected := 6.25
293 if math.Abs(result-expected) > 0.0001 {
294 t.Errorf("Power operation failed: expected %f, got %f", expected, result)
295 }
296 result, err = calculate("√ 2")
297 if err != nil {
298 t.Errorf("Unexpected error for square root: %v", err)
299 }
300 expected = math.Sqrt(2)
301 if math.Abs(result-expected) > 0.0001 {
302 t.Errorf("Square root operation failed: expected %f, got %f", expected, result)
303 }
304}
305func TestLargeNumbers(t *testing.T) {
306 result, err := calculate("1000000000 + 1000000000")
307 if err != nil {
308 t.Errorf("Unexpected error for adding large numbers: %v", err)
309 }
310 if result != 2000000000 {
311 t.Errorf("Adding large numbers failed: expected 2000000000, got %f", result)
312 }
313 result, err = calculate("1000000 * 1000000")
314 if err != nil {
315 t.Errorf("Unexpected error for multiplying large numbers: %v", err)
316 }
317 if result != 1000000000000 {
318 t.Errorf("Multiplying large numbers failed: expected 1000000000000, got %f", result)
319 }
320 result, err = calculate("2 ^ 30")
321 if err != nil {
322 t.Errorf("Unexpected error for large exponent operation: %v", err)
323 }
324 expected := math.Pow(2, 30)
325 if result != expected {
326 t.Errorf("Power operation with large exponent failed: expected %f, got %f", expected, result)
327 }
328 result, err = calculate("1000000000000 / 1000000")
329 if err != nil {
330 t.Errorf("Unexpected error for dividing large numbers: %v", err)
331 }
332 if result != 1000000 {
333 t.Errorf("Dividing large numbers failed: expected 1000000, got %f", result)
334 }
335}`;
336
337 const diffText = `--- original.go
338+++ updated.go
339@@ -30,6 +30,7 @@
340 fmt.Println(" / : Division")
341 fmt.Println(" ^ : Power")
342 fmt.Println(" √ : Square root (use only one number)")
343+ fmt.Println(" log: Logarithm (use 'log base number')")
344+ fmt.Println(" Base must be > 0 and != 1, number must be > 0")
345 for {
346 fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ")
347@@ -73,6 +74,8 @@
348 }
349 return math.Sqrt(num), nil
350 }
351+
352+ // Handle logarithmic operations
353+ if parts[0] == "log" {
354+ if len(parts) != 3 {
355+ return 0, fmt.Errorf("logarithm operation requires exactly two arguments: 'log base number'")
356+ }
357+ base, err := strconv.ParseFloat(parts[1], 64)
358+ if err != nil || base <= 0 || base == 1 {
359+ return 0, fmt.Errorf("invalid base for logarithm: must be > 0 and != 1")
360+ }
361+ num, err := strconv.ParseFloat(parts[2], 64)
362+ if err != nil || num <= 0 {
363+ return 0, fmt.Errorf("invalid number for logarithm: must be > 0")
364+ }
365+ return math.Log(num) / math.Log(base), nil
366+ }
367+
368 if len(parts) != 3 {
369 return 0, fmt.Errorf("invalid input format: please use 'number operator number'")
370@@ -155,6 +158,15 @@
371 }
372 }
373 }
374+
375+func TestLogarithmicCases(t *testing.T) {
376+ tests := []struct {
377+ input string
378+ expected float64
379+ hasError bool
380+ }{
381+ {"log 2 8", 3, false},
382+ {"log 10 100", 2, false},
383+ {"log 10 -5", 0, true},
384+ {"log 1 100", 0, true},
385+ {"log 0.5 0.25", 2, false},
386+ }`;
387 const result = applyUnifiedDiff(sourceCode, diffText);
388
389 expect(result[0].line).toEqual("package main");
390 // 1st block
391 expect(result[18].line).toEqual(
392 '\tfmt.Println(" √ : Square root (use only one number)")',
393 );
394 expect(result[19].line).toEqual(
395 " fmt.Println(\" log: Logarithm (use 'log base number')\")",
396 );
397 expect(result[20].line).toEqual(
398 ' fmt.Println(" Base must be > 0 and != 1, number must be > 0")',
399 );
400 // 2nd block
401 expect(result[56]).toEqual({ type: "same", line: "\t}" });
402 expect(result[57]).toEqual({ type: "new", line: "\t" });
403 expect(result[58]).toEqual({
404 type: "new",
405 line: "\t// Handle logarithmic operations",
406 });
407 expect(result[73]).toEqual({ type: "new", line: "" });
408 expect(result[74]).toEqual({
409 type: "same",
410 line: "\tif len(parts) != 3 {",
411 });
412 // 3rd block
413 expect(result[140]).toEqual({ type: "same", line: "}" });
414 expect(result[141]).toEqual({ type: "new", line: "" });
415 expect(result[142]).toEqual({
416 type: "new",
417 line: "func TestLogarithmicCases(t *testing.T) {",
418 });
419 expect(result[153]).toEqual({ type: "new", line: "\t}" });
420 expect(result[154]).toEqual({
421 type: "same",
422 line: "func TestSpecialCases(t *testing.T) {",
423 });
424 });
425
426 it("should throw error when hunk cannot be matched to source", () => {
427 const sourceCode = `line1
428line2
429line3`;
430
431 const diffText = `--- a.txt
432+++ b.txt
433@@ -1,3 +1,4 @@
434missing1
435-missing2
436+newline2
437missing3`;
438
439 expect(() => applyUnifiedDiff(sourceCode, diffText)).toThrow(
440 "Hunk could not be applied cleanly to source code.",
441 );
442 });
443});