Elffuss BraidHub

kikocis/continue public

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