簡體   English   中英

網站報告驗證錯誤,但代碼沒有

[英]The Website reports a validation error, but the code does not

我正在使用 fast-xml-parser,它試圖編寫一些測試用例,我在 Javascript 代碼中的一些純文本上失敗了。 但是,訪問該站點的在線網頁以嘗試驗證器,返回錯誤。

我的 XML 檢查

import * as XmlLib from 'fast-xml-parser';
class XmlWrapper {
    public static IsXML(XML: string): boolean | never {
        try {
            const XmlParser: XmlLib.XMLParser = new XmlLib.XMLParser({ allowBooleanAttributes: true });
            const _Result = XmlParser.parse(XML);

            // Just using the validate directly has the same issue
            // const _Result = XmlLib.XMLValidator.validate(XML, { allowBooleanAttributes: true });
            }
        } catch (Exception) {
            console.log(Exception);
            throw new Error('Bad XML');
        }
        return true;
    }
}

我的測試用例相當簡單:

import { XmlWrapper } from './xml-wrapper';

describe('XmlWrapper', () => {
    it('should be defined', () => {
        expect(new XmlWrapper()).toBeDefined();
    });

    it.each([
        ['undefined', undefined],
        ['null', null],
        ['empty string', ''],
        ['ABC', 'ABC'],
        ['just <?xml starting tag', '<?xml'],
    ])('should throw an exception when getting %s which is an invalid value.', (_Text, Value) => {
        expect(() => {
            XmlWrapper.IsXML(Value);
        }).toThrowError('Bad XML');
    });

除 ABC 字段外,所有測試均正確通過。

FAIL  src/library/wrappers/xml-wrapper.spec.ts (7.492 s)
XmlWrapper
    √ should throw an exception when getting undefined which is an invalid value. (7 ms)
    √ should throw an exception when getting null which is an invalid value. (3 ms)
    √ should throw an exception when getting empty string which is an invalid value. (3 ms)
    × should throw an exception when getting ABC which is an invalid value. (4 ms)
    √ should throw an exception when getting just <?xml starting tag which is an invalid value. (5 ms)

  ● XmlWrapper › should throw an exception when getting ABC which is an invalid value.
  expect(received).toThrowError(expected)

  Expected substring: "Bad XML"

  Received function did not throw

但是,使用fast-xml-parser 網頁,左側只有 ABC,然后是 Validate,可以正常工作。 僅使用 ABC 的快速 XML Parser 網頁

通過添加對對象鍵的檢查,我能夠檢測到用於 XML 驗證/解析的空 object。

import * as XmlLib from 'fast-xml-parser';
class XmlWrapper {
    public static IsXML(XML: string): boolean | never {
        try {
            const XmlParser: XmlLib.XMLParser = new XmlLib.XMLParser({ allowBooleanAttributes: true });
            const Result = XmlParser.parse(XML);

            if (Object.keys(Result).length) { // Empty structure
                return Result;
            }
            throw new Error('Bad XML');
        } catch (Exception) {
            console.log(Exception);
            throw new Error('Bad XML');
        }
        return true;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM