Skip to content

Commit

Permalink
fix: JSON data parsing with extras
Browse files Browse the repository at this point in the history
  • Loading branch information
mykola-mokhnach committed Sep 12, 2023
1 parent f9cbfd3 commit 3095bf9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
22 changes: 14 additions & 8 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -866,22 +866,28 @@ async function formatConfigMarker (configsGetter, desiredMarker, defaultMarker)
function parseJsonData (output, entityName) {
if (!/\bresult=-1\b/.test(output) || !/\bdata="/.test(output)) {
log.debug(output);
throw new Error(`Cannot retrieve ${entityName} from the device. ` +
'Check the server log for more details');
throw new Error(
`Cannot retrieve ${entityName} from the device. ` +
'Check the server log for more details'
);
}
const match = /\bdata=(".+)/.exec(output);
const match = /\bdata="(.+)",?/.exec(output);
if (!match) {
log.debug(output);
throw new Error(`Cannot parse ${entityName} from the command output. ` +
'Check the server log for more details');
throw new Error(
`Cannot parse ${entityName} from the command output. ` +
'Check the server log for more details'
);
}
const jsonStr = _.trim(match[1]).replace(/(^")|("$)/g, '');
const jsonStr = _.trim(match[1]);
try {
return JSON.parse(jsonStr);
} catch (e) {
log.debug(jsonStr);
throw new Error(`Cannot parse ${entityName} from the resulting data string. ` +
'Check the server log for more details');
throw new Error(
`Cannot parse ${entityName} from the resulting data string. ` +
'Check the server log for more details'
);
}
}

Expand Down
9 changes: 9 additions & 0 deletions test/unit/helper-specs.js
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,15 @@ describe('helpers', withMocks({fs}, function (mocks) {
items.length.should.eql(2);
total.should.eql(2);
});
it('should parse JSON received from broadcast output having extras', function () {
const broadcastOutput = `
Broadcasting: Intent { act=io.appium.settings.sms.read flg=0x400000 (has extras) }
Broadcast completed: result=-1, data="{"items":[{"id":"2","address":"+123456789","date":"1581936422203","read":"0","status":"-1","type":"1","body":"\\"text message2\\""},{"id":"1","address":"+123456789","date":"1581936382740","read":"0","status":"-1","type":"1","body":"\\"text message\\""}],"total":2}", extras: Bundle[mParcelledData.dataSize=52]
`;
const {items, total} = parseJsonData(broadcastOutput, '');
items.length.should.eql(2);
total.should.eql(2);
});
it('should throw an error if json retrieval fails', function () {
const broadcastOutput = `
Broadcasting: Intent { act=io.appium.settings.sms.read flg=0x400000 (has extras) }
Expand Down

0 comments on commit 3095bf9

Please sign in to comment.