utils.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /* globals document, atob, Blob, URL */
  6. import VirtualTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/virtualtesteditor';
  7. import ClassicTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/classictesteditor';
  8. import normalizeHtml from '@ckeditor/ckeditor5-utils/tests/_utils/normalizehtml';
  9. import { setData, stringify as stringifyModel } from '@ckeditor/ckeditor5-engine/src/dev-utils/model';
  10. import { stringify as stringifyView } from '@ckeditor/ckeditor5-engine/src/dev-utils/view';
  11. import { fixtures, browserFixtures } from './fixtures';
  12. /**
  13. * Mocks dataTransfer object which can be used for simulating paste.
  14. *
  15. * @param {Object} data Object containing 'mime type - data' pairs.
  16. * @returns {Object} DataTransfer mock object.
  17. */
  18. export function createDataTransfer( data ) {
  19. return {
  20. getData( type ) {
  21. return data[ type ];
  22. }
  23. };
  24. }
  25. /**
  26. * Generates test groups based on provided parameters. Generated tests are specifically designed
  27. * to test pasted content transformations.
  28. *
  29. * This function generates test groups based on available fixtures:
  30. *
  31. * 1. If only generic fixtures are available they will be used for all listed browsers and combined into one test group.
  32. * 2. If there are browser-specific fixtures available they will be used for matching browser resulting in a separate
  33. * test group. All unmatched browsers will use generic fixtures combined into one separate test group.
  34. * 3. If some fixtures are marked to be skipped for a specific browser, the separate test group will be created for this browser.
  35. *
  36. * @param {Object} config
  37. * @param {String} config.type Type of tests to generate, could be 'normalization' or 'integration'.
  38. * @param {String} config.input Name of the fixtures group. Usually stored in `/tests/_data/groupname/`.
  39. * @param {Array.<String>} config.browsers List of all browsers for which to generate tests.
  40. * @param {Object} [config.editorConfig] Editor config which is passed to editor `create()` method.
  41. * @param {Object} [config.skip] List of fixtures for any browser to skip. The supported format is:
  42. *
  43. * {
  44. * browserName: [ fixtureName1, fixtureName2 ]
  45. * }
  46. *
  47. * @param {Boolean} [config.withBlobsHandling = false] If special flow with generating and asserting blob URLs data
  48. * should be used. This param has effect only for integration tests.
  49. */
  50. export function generateTests( config ) {
  51. if ( [ 'normalization', 'integration' ].indexOf( config.type ) === -1 ) {
  52. throw new Error( `Invalid tests type - \`config.type\`: '${ config.type }'.` );
  53. }
  54. if ( !config.input ) {
  55. throw new Error( 'No `config.input` option provided.' );
  56. }
  57. if ( !config.browsers || !config.browsers.length ) {
  58. throw new Error( 'No or empty `config.browsers` option provided.' );
  59. }
  60. const withBlobsHandling = config.withBlobsHandling || false;
  61. const groups = groupFixturesByBrowsers( config.browsers, config.input, config.skip );
  62. const generateSuiteFn = config.type === 'normalization' ? generateNormalizationTests : generateIntegrationTests;
  63. describe( config.type, () => {
  64. describe( config.input, () => {
  65. const editorConfig = config.editorConfig || {};
  66. for ( const group of Object.keys( groups ) ) {
  67. const skip = config.skip && config.skip[ group ] ? config.skip[ group ] : [];
  68. if ( groups[ group ] ) {
  69. generateSuiteFn( group, groups[ group ], editorConfig, skip, withBlobsHandling );
  70. }
  71. }
  72. } );
  73. } );
  74. }
  75. // Creates browser groups combining all browsers using same fixtures. Each browser which have
  76. // some fixtures marked to be skipped automatically create separate groups.
  77. //
  78. // @param {Array.<String>} browsers List of all browsers for which fixture groups will be created.
  79. // @param {String} fixturesGroup Fixtures group name.
  80. // @returns {Object} Object containing browsers groups where key is the name of the group and value is fixtures object:
  81. //
  82. // {
  83. // 'safari': { ... }
  84. // 'edge': { ... }
  85. // 'chrome, firefox': { ... }
  86. // }
  87. function groupFixturesByBrowsers( browsers, fixturesGroup, skipBrowsers ) {
  88. const browsersGroups = {};
  89. const browsersGeneric = browsers.slice( 0 );
  90. // Create separate groups for browsers with browser-specific fixtures available.
  91. for ( const browser of browsers ) {
  92. if ( browserFixtures[ fixturesGroup ] && browserFixtures[ fixturesGroup ][ browser ] ) {
  93. browsersGroups[ browser ] = browserFixtures[ fixturesGroup ][ browser ];
  94. browsersGeneric.splice( browsersGeneric.indexOf( browser ), 1 );
  95. }
  96. }
  97. // Create separate groups for browsers with skipped tests.
  98. if ( skipBrowsers ) {
  99. for ( const browser of Object.keys( skipBrowsers ) ) {
  100. if ( browsersGeneric.indexOf( browser ) !== -1 ) {
  101. browsersGroups[ browser ] = fixtures[ fixturesGroup ] ? fixtures[ fixturesGroup ] : null;
  102. browsersGeneric.splice( browsersGeneric.indexOf( browser ), 1 );
  103. }
  104. }
  105. }
  106. // Use generic fixtures (if available) for browsers left.
  107. if ( browsersGeneric.length ) {
  108. browsersGroups[ browsersGeneric.join( ', ' ) ] = fixtures[ fixturesGroup ] ? fixtures[ fixturesGroup ] : null;
  109. }
  110. return browsersGroups;
  111. }
  112. // Generates normalization tests based on a provided fixtures. For each input fixture one test is generated.
  113. //
  114. // @param {String} title Tests group title.
  115. // @param {Object} fixtures Object containing fixtures.
  116. // @param {Object} editorConfig Editor config with which test editor will be created.
  117. // @param {Array.<String>} skip Array of fixtures names which tests should be skipped.
  118. function generateNormalizationTests( title, fixtures, editorConfig, skip ) {
  119. describe( title, () => {
  120. let editor, pasteFromOfficePlugin;
  121. beforeEach( () => {
  122. return VirtualTestEditor
  123. .create( editorConfig )
  124. .then( newEditor => {
  125. editor = newEditor;
  126. pasteFromOfficePlugin = editor.plugins.get( 'PasteFromOffice' );
  127. } );
  128. } );
  129. afterEach( () => {
  130. editor.destroy();
  131. pasteFromOfficePlugin = null;
  132. } );
  133. for ( const name of Object.keys( fixtures.input ) ) {
  134. ( skip.indexOf( name ) !== -1 ? it.skip : it )( name, () => {
  135. const dataTransfer = createDataTransfer( {
  136. 'text/rtf': fixtures.inputRtf && fixtures.inputRtf[ name ]
  137. } );
  138. expectNormalized(
  139. pasteFromOfficePlugin._normalizeWordInput( fixtures.input[ name ], dataTransfer ),
  140. fixtures.normalized[ name ]
  141. );
  142. } );
  143. }
  144. } );
  145. }
  146. // Generates integration tests based on a provided fixtures. For each input fixture one test is generated.
  147. //
  148. // @param {String} title Tests group title.
  149. // @param {Object} fixtures Object containing fixtures.
  150. // @param {Object} editorConfig Editor config with which test editor will be created.
  151. // @param {Array.<String>} skip Array of fixtures names which tests should be skipped.
  152. // @param {Boolean} [withBlobsHandling = false] If special `expectModelWithBlobs()` function should be used to assert model data.
  153. function generateIntegrationTests( title, fixtures, editorConfig, skip, withBlobsHandling ) {
  154. describe( title, () => {
  155. let element, editor;
  156. let data = {};
  157. before( () => {
  158. element = document.createElement( 'div' );
  159. document.body.appendChild( element );
  160. return ClassicTestEditor
  161. .create( element, editorConfig )
  162. .then( editorInstance => {
  163. editor = editorInstance;
  164. } );
  165. } );
  166. beforeEach( () => {
  167. setData( editor.model, '<paragraph>[]</paragraph>' );
  168. const editorModel = editor.model;
  169. const insertContent = editorModel.insertContent;
  170. data = {};
  171. sinon.stub( editorModel, 'insertContent' ).callsFake( ( content, selection ) => {
  172. // Save model string representation now as it may change after `insertContent()` function call
  173. // so accessing it later may not work as it may have emptied/changed structure.
  174. data.actual = stringifyModel( content );
  175. insertContent.call( editorModel, content, selection );
  176. } );
  177. } );
  178. afterEach( () => {
  179. sinon.restore();
  180. } );
  181. after( () => {
  182. editor.destroy();
  183. element.remove();
  184. } );
  185. for ( const name of Object.keys( fixtures.input ) ) {
  186. if ( !withBlobsHandling ) {
  187. ( skip.indexOf( name ) !== -1 ? it.skip : it )( name, () => {
  188. data.input = fixtures.input[ name ];
  189. data.model = fixtures.model[ name ];
  190. expectModel( data, editor, fixtures.inputRtf && fixtures.inputRtf[ name ] );
  191. } );
  192. } else {
  193. ( skip.indexOf( name ) !== -1 ? it.skip : it )( name, done => {
  194. data.input = fixtures.input[ name ];
  195. data.model = fixtures.model[ name ];
  196. expectModelWithBlobs( data, editor, fixtures.inputBlob && fixtures.inputBlob[ name ], done );
  197. } );
  198. }
  199. }
  200. } );
  201. }
  202. // Checks if provided view element instance equals expected HTML. The element is stringified
  203. // before comparing so its entire structure can be compared.
  204. // If the given `actual` or `expected` structure contains base64 encoded images,
  205. // these images are extracted (so HTML diff is readable) and compared
  206. // one by one separately (so it is visible if base64 representation is malformed).
  207. //
  208. // This function is designed for comparing normalized data so expected input is preprocessed before comparing:
  209. //
  210. // * Tabs on the lines beginnings are removed.
  211. // * Line breaks and empty lines are removed.
  212. //
  213. // The expected input should be prepared in the above in mind which means every element containing text nodes must start
  214. // and end in the same line. So expected input may be formatted like:
  215. //
  216. // <span lang=PL style='mso-ansi-language:PL'> 03<span style='mso-spacerun:yes'> </span><o:p></o:p></span>
  217. //
  218. // but not like:
  219. //
  220. // <span lang=PL style='mso-ansi-language:PL'>
  221. // 03<span style='mso-spacerun:yes'> </span>
  222. // <o:p></o:p>
  223. // </span>
  224. //
  225. // because tab preceding `03` text will be treated as formatting character and will be removed.
  226. //
  227. // @param {module:engine/view/text~Text|module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment}
  228. // actualView Actual HTML.
  229. // @param {String} expectedHtml Expected HTML.
  230. function expectNormalized( actualView, expectedHtml ) {
  231. // We are ok with both spaces and non-breaking spaces in the actual content.
  232. // Replace `&nbsp;` with regular spaces to align with expected content.
  233. const actualNormalized = stringifyView( actualView ).replace( /\u00A0/g, ' ' );
  234. const expectedNormalized = normalizeHtml( inlineData( expectedHtml ) );
  235. compareContentWithBase64Images( actualNormalized, expectedNormalized );
  236. }
  237. // Compares two models string representations. The input HTML is processed through paste
  238. // pipeline where it is transformed into model. This function hooks into {@link module:engine/model/model~Model#insertContent}
  239. // to get the model representation before it is inserted.
  240. //
  241. // @param {Object} data
  242. // @param {String} data.input Input HTML which will be pasted into the editor.
  243. // @param {String} data.actual Actual model data.
  244. // @param {String} data.model Expected model data.
  245. // @param {module:core/editor/editor~Editor} editor Editor instance.
  246. // @param {String} [inputRtf] Additional RTF input data which will be pasted into the editor as `text/rtf` together with regular input data.
  247. function expectModel( data, editor, inputRtf = null ) {
  248. firePasteEvent( editor, {
  249. 'text/html': data.input,
  250. 'text/rtf': inputRtf
  251. } );
  252. compareContentWithBase64Images( data.actual, inlineData( data.model ) );
  253. }
  254. // Compares two models string representations. The input HTML is processed through paste
  255. // pipeline where it is transformed into model. This function hooks into {@link module:engine/model/model~Model#insertContent}
  256. // to get the model representation before it is inserted.
  257. //
  258. // @param {Object} data
  259. // @param {String} data.input Input HTML which will be pasted into the editor.
  260. // @param {String} data.actual Actual model data.
  261. // @param {String} data.model Expected model data.
  262. // @param {module:core/editor/editor~Editor} editor Editor instance.
  263. // @param {String} inputBlobs Additional data which will be used to generate blobs for a test.
  264. // @param {Function} done The callback function which should be called when test has finished.
  265. function expectModelWithBlobs( data, editor, inputBlobs, done ) {
  266. // If the browser stores images as blob urls, we need to generate blobs based on a provided images base64 data
  267. // and then replace original blob urls with the local ones. This allows Paste from Office to correctly extract
  268. // data checking if the transformations flow works in real use cases.
  269. const base64 = inputBlobs.split( '------' ).map( item => item.replace( /\s/g, '' ) );
  270. const blobUrls = createBlobsFromBase64Data( base64 );
  271. const input = replaceBlobUrls( data.input, blobUrls );
  272. const expected = replaceBlobUrls( inlineData( data.model ), blobUrls );
  273. let counter = 0;
  274. const onChange = function() {
  275. counter++;
  276. // Each blob is fetched asynchronously generating separate `change` event. Also first content insertion
  277. // (with blob urls still) generates one `change` event. This means the content is fully transformed when
  278. // number of change events is number of blob urls in the content + 1.
  279. if ( counter > blobUrls.length ) {
  280. editor.editing.model.document.off( 'change', onChange );
  281. counter = 0;
  282. const expectedData = replaceBlobUrls( expected, base64 );
  283. const actualData = replaceBlobUrls( data.actual, base64 );
  284. try {
  285. compareContentWithBase64Images( actualData, expectedData );
  286. done();
  287. } catch ( err ) {
  288. done( err );
  289. }
  290. }
  291. };
  292. editor.editing.model.document.on( 'change', onChange );
  293. firePasteEvent( editor, {
  294. 'text/html': input
  295. } );
  296. // In some rare cases there might be `&nbsp;` in a model data
  297. // (see https://github.com/ckeditor/ckeditor5-paste-from-office/issues/27).
  298. data.actual = data.actual.replace( /\u00A0/g, ' ' );
  299. // Check if initial data with blob urls is correct.
  300. expect( data.actual ).to.equal( expected );
  301. }
  302. // Compares actual and expected content. Before comparison the base64 images data is extracted so data diff is more readable.
  303. // If there were any images extracted their base64 data is also compared.
  304. //
  305. // @param {String} actual Actual content.
  306. // @param {String} expected Expected content.
  307. function compareContentWithBase64Images( actual, expected ) {
  308. // Extract base64 images so they do not pollute model diff and can be compared separately.
  309. const { data: actualModel, images: actualImages } = extractBase64Srcs( actual );
  310. const { data: expectedModel, images: expectedImages } = extractBase64Srcs( expected );
  311. expect( actualModel ).to.equal( expectedModel );
  312. if ( actualImages.length > 0 && expectedImages.length > 0 ) {
  313. expect( actualImages.length ).to.equal( expectedImages.length );
  314. expect( actualImages ).to.deep.equal( expectedImages );
  315. }
  316. }
  317. // Inlines given HTML / model representation string by removing preceding tabs and line breaks.
  318. //
  319. // @param {String} data Data to be inlined.
  320. function inlineData( data ) {
  321. return data
  322. // Replace tabs on the lines beginning as normalized input files are formatted.
  323. .replace( /^\t*</gm, '<' )
  324. // Replace line breaks (after closing tags) too.
  325. .replace( /[\r\n]/gm, '' );
  326. }
  327. // Extracts base64 part representing an image from the given HTML / model representation.
  328. //
  329. // @param {String} data Data from which bas64 strings will be extracted.
  330. // @returns {Object} result
  331. // @returns {String} result.data Data without bas64 strings.
  332. // @returns {Array.<String>} result.images Array of extracted base64 strings.
  333. function extractBase64Srcs( data ) {
  334. const regexp = /src="data:image\/(png|jpe?g);base64,([^"]*)"/gm;
  335. const images = [];
  336. const replacements = [];
  337. let match;
  338. while ( ( match = regexp.exec( data ) ) !== null ) {
  339. images.push( match[ 2 ].toLowerCase() );
  340. replacements.push( match[ 2 ] );
  341. }
  342. for ( const replacement of replacements ) {
  343. data = data.replace( replacement, '' );
  344. }
  345. return { data, images };
  346. }
  347. // Fires paste event on a given editor instance with a specific HTML data.
  348. //
  349. // @param {module:core/editor/editor~Editor} editor Editor instance on which paste event will be fired.
  350. // @param {Object} data Object with `type: content` pairs used as data transfer data in the fired paste event.
  351. function firePasteEvent( editor, data ) {
  352. editor.editing.view.document.fire( 'paste', {
  353. dataTransfer: createDataTransfer( data ),
  354. preventDefault() {}
  355. } );
  356. }
  357. // Replaces all blob urls (`blob:`) in the given HTML with given replacements data.
  358. //
  359. // @param {String} html The HTML data in which blob urls will be replaced.
  360. // @param {Array.<String>} replacements Array of string which will replace found blobs in the order of occurrence.
  361. // @returns {String} The HTML data with all blob urls replaced.
  362. function replaceBlobUrls( html, replacements ) {
  363. const blobRegexp = /src="(blob:[^"]*)"/g;
  364. const toReplace = [];
  365. let match;
  366. while ( ( match = blobRegexp.exec( html ) ) !== null ) {
  367. toReplace.push( match[ 1 ] );
  368. }
  369. for ( let i = 0; i < toReplace.length; i++ ) {
  370. if ( replacements[ i ] ) {
  371. html = html.replace( toReplace[ i ], replacements[ i ] );
  372. }
  373. }
  374. return html;
  375. }
  376. // Creates blob urls from the given base64 data.
  377. //
  378. // @param {Array.<String>} base64Data Array of base64 strings from which blob urls will be generated.
  379. // @returns {Array} Array of generated blob urls.
  380. function createBlobsFromBase64Data( base64Data ) {
  381. const blobUrls = [];
  382. for ( const data of base64Data ) {
  383. blobUrls.push( URL.createObjectURL( base64toBlob( data.trim() ) ) );
  384. }
  385. return blobUrls;
  386. }
  387. // Transforms base64 data into a blob object.
  388. //
  389. // @param {String} The base64 data to be transformed.
  390. // @returns {Blob} Blob object representing given base64 data.
  391. function base64toBlob( base64Data ) {
  392. const [ type, data ] = base64Data.split( ',' );
  393. const byteCharacters = atob( data );
  394. const byteArrays = [];
  395. for ( let offset = 0; offset < byteCharacters.length; offset += 512 ) {
  396. const slice = byteCharacters.slice( offset, offset + 512 );
  397. const byteNumbers = new Array( slice.length );
  398. for ( let i = 0; i < slice.length; i++ ) {
  399. byteNumbers[ i ] = slice.charCodeAt( i );
  400. }
  401. byteArrays.push( new Uint8Array( byteNumbers ) );
  402. }
  403. return new Blob( byteArrays, { type } );
  404. }