import { test, expect } from 'bun:test'; import { createAccountHTTP, type AccountCapture } from '../scripts/lib/openobserve-account-http'; const request={captureId:'fixture-create',path:'/api/default/service_accounts',method:'POST',body:{email:'fixture@example.invalid'},auth:'fixture-only'}; const bytes=(value:string)=>new TextEncoder().encode(value); test('malformed one-time response is captured before JSON decoding fails',async()=>{ const captures:AccountCapture[]=[];const raw=bytes('{"token":"fixture-once",'); const call=createAccountHTTP({request:async()=>({status:200,chunks:(async function*(){yield raw})()}),capture:async r=>{captures.push(r)}},1000); await expect(call(request)).rejects.toThrow();expect(captures).toHaveLength(1);expect(captures[0].raw).toEqual(raw);expect(captures[0].status).toBe(200); }); test('partial response is retained as uncertain when body reading fails',async()=>{ const captures:AccountCapture[]=[];const raw=bytes('{"token":"fixture-partial'); const call=createAccountHTTP({request:async()=>({status:200,chunks:(async function*(){yield raw;throw new Error('synthetic truncated body')})()}),capture:async r=>{captures.push(r)}},1000); await expect(call(request)).rejects.toThrow();expect(captures).toHaveLength(1);expect(captures[0].raw).toEqual(raw);expect(captures[0].complete).toBe(false);expect(captures[0].outcome).toBe('body_uncertain'); }); test('oversized response retains bounded available bytes before reporting its cap',async()=>{ const captures:AccountCapture[]=[];const call=createAccountHTTP({request:async()=>({status:200,chunks:(async function*(){yield bytes('123456')})()}),capture:async r=>{captures.push(r)}},4); await expect(call(request)).rejects.toThrow();expect(captures).toHaveLength(1);expect(captures[0].raw).toEqual(bytes('1234'));expect(captures[0].outcome).toBe('size_exceeded');expect(captures[0].complete).toBe(false); }); test('network failure records uncertain request without retry',async()=>{ const captures:AccountCapture[]=[];let calls=0;const call=createAccountHTTP({request:async()=>{calls++;throw new Error('synthetic network failure')},capture:async r=>{captures.push(r)}},1000); await expect(call(request)).rejects.toThrow();expect(calls).toBe(1);expect(captures).toHaveLength(1);expect(captures[0].status).toBeNull();expect(captures[0].outcome).toBe('network_uncertain'); }); test('valid response is captured before it is returned to the create caller',async()=>{ const captures:AccountCapture[]=[];const raw=bytes('{"code":200,"token":"fixture-valid"}');const call=createAccountHTTP({request:async()=>({status:200,chunks:(async function*(){yield raw})()}),capture:async r=>{captures.push(r)}},1000); const result=await call(request);expect(captures).toHaveLength(1);expect(captures[0].raw).toEqual(raw);expect(result.body.token).toBe('fixture-valid'); });