utils.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* globals document */
  6. import VirtualTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/virtualtesteditor';
  7. import ClassicTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/classictesteditor';
  8. import PasteFromOffice from '../../src/pastefromoffice';
  9. import HtmlDataProcessor from '@ckeditor/ckeditor5-engine/src/dataprocessor/htmldataprocessor';
  10. import normalizeClipboardData from '@ckeditor/ckeditor5-clipboard/src/utils/normalizeclipboarddata';
  11. import normalizeHtml from '@ckeditor/ckeditor5-utils/tests/_utils/normalizehtml';
  12. import { setData, stringify as stringifyModel } from '@ckeditor/ckeditor5-engine/src/dev-utils/model';
  13. import { stringify as stringifyView } from '@ckeditor/ckeditor5-engine/src/dev-utils/view';
  14. import { fixtures, browserFixtures } from './fixtures';
  15. /**
  16. * Mocks dataTransfer object which can be used for simulating paste.
  17. *
  18. * @param {Object} data Object containing 'mime type - data' pairs.
  19. * @returns {Object} DataTransfer mock object.
  20. */
  21. export function createDataTransfer( data ) {
  22. return {
  23. getData( type ) {
  24. return data[ type ];
  25. }
  26. };
  27. }
  28. /**
  29. * Generates test groups based on provided parameters. Generated tests are specifically designed
  30. * to test pasted content transformations.
  31. *
  32. * This function generates test groups based on available fixtures:
  33. *
  34. * 1. If only generic fixtures are available they will be used for all listed browsers and combined into one test group.
  35. * 2. If there are browser-specific fixtures available they will be used for matching browser resulting in a separate
  36. * test group. All unmatched browsers will use generic fixtures combined into one separate test group.
  37. * 3. If some fixtures are marked to be skipped for a specific browser, the separate test group will be created for this browser.
  38. *
  39. * @param {Object} config
  40. * @param {String} config.type Type of tests to generate, could be 'normalization' or 'integration'.
  41. * @param {String} config.input Name of the fixtures group. Usually stored in `/tests/_data/groupname/`.
  42. * @param {String} config.dataSource Name of the office app, which was used to generate data.
  43. * @param {Array.<String>} config.browsers List of all browsers for which to generate tests.
  44. * @param {Object} [config.editorConfig] Editor config which is passed to editor `create()` method.
  45. * @param {Object} [config.skip] List of fixtures for any browser to skip. The supported format is:
  46. *
  47. * {
  48. * browserName: [ fixtureName1, fixtureName2 ]
  49. * }
  50. */
  51. export function generateTests( config ) {
  52. if ( [ 'normalization', 'integration' ].indexOf( config.type ) === -1 ) {
  53. throw new Error( `Invalid tests type - \`config.type\`: '${ config.type }'.` );
  54. }
  55. if ( !config.dataSource ) {
  56. throw new Error( 'No `config.dataSource` option provided.' );
  57. }
  58. if ( !config.input ) {
  59. throw new Error( 'No `config.input` option provided.' );
  60. }
  61. if ( !config.browsers || !config.browsers.length ) {
  62. throw new Error( 'No or empty `config.browsers` option provided.' );
  63. }
  64. const groups = groupFixturesByBrowsers( config.browsers, config.input, config.skip );
  65. const generateSuiteFn = config.type === 'normalization' ? generateNormalizationTests : generateIntegrationTests;
  66. describe( config.type, () => {
  67. describe( config.dataSource, () => {
  68. describe( config.input, () => {
  69. const editorConfig = config.editorConfig || {};
  70. for ( const group of Object.keys( groups ) ) {
  71. const skip = config.skip && config.skip[ group ] ? config.skip[ group ] : [];
  72. if ( groups[ group ] ) {
  73. generateSuiteFn( group, groups[ group ], editorConfig, skip );
  74. }
  75. }
  76. } );
  77. } );
  78. } );
  79. }
  80. // Creates browser groups combining all browsers using same fixtures. Each browser which have
  81. // some fixtures marked to be skipped automatically create separate groups.
  82. //
  83. // @param {Array.<String>} browsers List of all browsers for which fixture groups will be created.
  84. // @param {String} fixturesGroup Fixtures group name.
  85. // @returns {Object} Object containing browsers groups where key is the name of the group and value is fixtures object:
  86. //
  87. // {
  88. // 'safari': { ... }
  89. // 'edge': { ... }
  90. // 'chrome, firefox': { ... }
  91. // }
  92. function groupFixturesByBrowsers( browsers, fixturesGroup, skipBrowsers ) {
  93. const browsersGroups = {};
  94. const browsersGeneric = browsers.slice( 0 );
  95. // Create separate groups for browsers with browser-specific fixtures available.
  96. for ( const browser of browsers ) {
  97. if ( browserFixtures[ fixturesGroup ] && browserFixtures[ fixturesGroup ][ browser ] ) {
  98. browsersGroups[ browser ] = browserFixtures[ fixturesGroup ][ browser ];
  99. browsersGeneric.splice( browsersGeneric.indexOf( browser ), 1 );
  100. }
  101. }
  102. // Create separate groups for browsers with skipped tests.
  103. if ( skipBrowsers ) {
  104. for ( const browser of Object.keys( skipBrowsers ) ) {
  105. if ( browsersGeneric.indexOf( browser ) !== -1 ) {
  106. browsersGroups[ browser ] = fixtures[ fixturesGroup ] ? fixtures[ fixturesGroup ] : null;
  107. browsersGeneric.splice( browsersGeneric.indexOf( browser ), 1 );
  108. }
  109. }
  110. }
  111. // Use generic fixtures (if available) for browsers left.
  112. if ( browsersGeneric.length ) {
  113. browsersGroups[ browsersGeneric.join( ', ' ) ] = fixtures[ fixturesGroup ] ? fixtures[ fixturesGroup ] : null;
  114. }
  115. return browsersGroups;
  116. }
  117. // Generates normalization tests based on a provided fixtures. For each input fixture one test is generated.
  118. // Please notice that normalization compares generated Views, not DOM. That's why there might appear some not familiar structures,
  119. // like closing tags for void tags, for example `<br></br>`.
  120. //
  121. // @param {String} title Tests group title.
  122. // @param {Object} fixtures Object containing fixtures.
  123. // @param {Object} editorConfig Editor config with which test editor will be created.
  124. // @param {Array.<String>} skip Array of fixtures names which tests should be skipped.
  125. function generateNormalizationTests( title, fixtures, editorConfig, skip ) {
  126. const htmlDataProcessor = new HtmlDataProcessor();
  127. describe( title, () => {
  128. let editor;
  129. beforeEach( () => {
  130. return VirtualTestEditor
  131. .create( editorConfig )
  132. .then( newEditor => {
  133. editor = newEditor;
  134. } );
  135. } );
  136. afterEach( () => {
  137. editor.destroy();
  138. } );
  139. for ( const name of Object.keys( fixtures.input ) ) {
  140. ( skip.indexOf( name ) !== -1 ? it.skip : it )( name, () => {
  141. // Simulate data from Clipboard event
  142. const data = {
  143. content: htmlDataProcessor.toView( normalizeClipboardData( fixtures.input[ name ] ) ),
  144. dataTransfer: createDataTransfer( {
  145. 'text/html': fixtures.input[ name ],
  146. 'text/rtf': fixtures.inputRtf && fixtures.inputRtf[ name ]
  147. } )
  148. };
  149. PasteFromOffice._inputTransformationListener( null, data );
  150. expectNormalized(
  151. data.content,
  152. fixtures.normalized[ name ]
  153. );
  154. } );
  155. }
  156. } );
  157. }
  158. // Generates integration tests based on a provided fixtures. For each input fixture one test is generated.
  159. //
  160. // @param {String} title Tests group title.
  161. // @param {Object} fixtures Object containing fixtures.
  162. // @param {Object} editorConfig Editor config with which test editor will be created.
  163. // @param {Array.<String>} skip Array of fixtures names which tests should be skipped.
  164. function generateIntegrationTests( title, fixtures, editorConfig, skip ) {
  165. describe( title, () => {
  166. let element, editor;
  167. let data = {};
  168. before( () => {
  169. element = document.createElement( 'div' );
  170. document.body.appendChild( element );
  171. return ClassicTestEditor
  172. .create( element, editorConfig )
  173. .then( editorInstance => {
  174. editor = editorInstance;
  175. } );
  176. } );
  177. beforeEach( () => {
  178. setData( editor.model, '<paragraph>[]</paragraph>' );
  179. const editorModel = editor.model;
  180. const insertContent = editorModel.insertContent;
  181. data = {};
  182. sinon.stub( editorModel, 'insertContent' ).callsFake( ( content, selection ) => {
  183. // Save model string representation now as it may change after `insertContent()` function call
  184. // so accessing it later may not work as it may have emptied/changed structure.
  185. data.actual = stringifyModel( content );
  186. insertContent.call( editorModel, content, selection );
  187. } );
  188. } );
  189. afterEach( () => {
  190. sinon.restore();
  191. } );
  192. after( () => {
  193. editor.destroy();
  194. element.remove();
  195. } );
  196. for ( const name of Object.keys( fixtures.input ) ) {
  197. ( skip.indexOf( name ) !== -1 ? it.skip : it )( name, () => {
  198. data.input = fixtures.input[ name ];
  199. data.model = fixtures.model[ name ];
  200. expectModel( data, editor, fixtures.inputRtf && fixtures.inputRtf[ name ] );
  201. } );
  202. }
  203. } );
  204. }
  205. // Checks if provided view element instance equals expected HTML. The element is stringified
  206. // before comparing so its entire structure can be compared.
  207. // If the given `actual` or `expected` structure contains base64 encoded images,
  208. // these images are extracted (so HTML diff is readable) and compared
  209. // one by one separately (so it is visible if base64 representation is malformed).
  210. //
  211. // This function is designed for comparing normalized data so expected input is preprocessed before comparing:
  212. //
  213. // * Tabs on the lines beginnings are removed.
  214. // * Line breaks and empty lines are removed.
  215. //
  216. // The expected input should be prepared in the above in mind which means every element containing text nodes must start
  217. // and end in the same line. So expected input may be formatted like:
  218. //
  219. // <span lang=PL style='mso-ansi-language:PL'> 03<span style='mso-spacerun:yes'> </span><o:p></o:p></span>
  220. //
  221. // but not like:
  222. //
  223. // <span lang=PL style='mso-ansi-language:PL'>
  224. // 03<span style='mso-spacerun:yes'> </span>
  225. // <o:p></o:p>
  226. // </span>
  227. //
  228. // because tab preceding `03` text will be treated as formatting character and will be removed.
  229. //
  230. // @param {module:engine/view/text~Text|module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment}
  231. // actualView Actual HTML.
  232. // @param {String} expectedHtml Expected HTML.
  233. function expectNormalized( actualView, expectedHtml ) {
  234. // We are ok with both spaces and non-breaking spaces in the actual content.
  235. // Replace `&nbsp;` with regular spaces to align with expected content.
  236. const actualNormalized = stringifyView( actualView ).replace( /\u00A0/g, ' ' );
  237. const expectedNormalized = normalizeHtml( inlineData( expectedHtml ) );
  238. compareContentWithBase64Images( actualNormalized, expectedNormalized );
  239. }
  240. // Compares two models string representations. The input HTML is processed through paste
  241. // pipeline where it is transformed into model. This function hooks into {@link module:engine/model/model~Model#insertContent}
  242. // to get the model representation before it is inserted.
  243. //
  244. // @param {Object} data
  245. // @param {String} data.input Input HTML which will be pasted into the editor.
  246. // @param {String} data.actual Actual model data.
  247. // @param {String} data.model Expected model data.
  248. // @param {module:core/editor/editor~Editor} editor Editor instance.
  249. // @param {String} [inputRtf] Additional RTF input data which will be pasted into the editor as `text/rtf` together with regular input data.
  250. function expectModel( data, editor, inputRtf = null ) {
  251. firePasteEvent( editor, {
  252. 'text/html': data.input,
  253. 'text/rtf': inputRtf
  254. } );
  255. compareContentWithBase64Images( data.actual, inlineData( data.model ) );
  256. }
  257. // Compares actual and expected content. Before comparison the base64 images data is extracted so data diff is more readable.
  258. // If there were any images extracted their base64 data is also compared.
  259. //
  260. // @param {String} actual Actual content.
  261. // @param {String} expected Expected content.
  262. function compareContentWithBase64Images( actual, expected ) {
  263. // Extract base64 images so they do not pollute model diff and can be compared separately.
  264. const { data: actualModel, images: actualImages } = extractBase64Srcs( actual );
  265. const { data: expectedModel, images: expectedImages } = extractBase64Srcs( expected );
  266. // In some rare cases there might be `&nbsp;` in a model data
  267. // (see https://github.com/ckeditor/ckeditor5-paste-from-office/issues/27).
  268. expect( actualModel.replace( /\u00A0/g, ' ' ) ).to.equal( expectedModel );
  269. if ( actualImages.length > 0 && expectedImages.length > 0 ) {
  270. expect( actualImages.length ).to.equal( expectedImages.length );
  271. expect( actualImages ).to.deep.equal( expectedImages );
  272. }
  273. }
  274. // Inlines given HTML / model representation string by removing preceding tabs and line breaks.
  275. //
  276. // @param {String} data Data to be inlined.
  277. function inlineData( data ) {
  278. return data
  279. // Replace tabs on the lines beginning as normalized input files are formatted.
  280. .replace( /^\t*</gm, '<' )
  281. // Replace line breaks (after closing tags) too.
  282. .replace( /[\r\n]/gm, '' );
  283. }
  284. // Extracts base64 part representing an image from the given HTML / model representation.
  285. //
  286. // @param {String} data Data from which bas64 strings will be extracted.
  287. // @returns {Object} result
  288. // @returns {String} result.data Data without bas64 strings.
  289. // @returns {Array.<String>} result.images Array of extracted base64 strings.
  290. function extractBase64Srcs( data ) {
  291. const regexp = /src="data:image\/(png|jpe?g);base64,([^"]*)"/gm;
  292. const images = [];
  293. const replacements = [];
  294. let match;
  295. while ( ( match = regexp.exec( data ) ) !== null ) {
  296. images.push( match[ 2 ].toLowerCase() );
  297. replacements.push( match[ 2 ] );
  298. }
  299. for ( const replacement of replacements ) {
  300. data = data.replace( replacement, '' );
  301. }
  302. return { data, images };
  303. }
  304. // Fires paste event on a given editor instance with a specific HTML data.
  305. //
  306. // @param {module:core/editor/editor~Editor} editor Editor instance on which paste event will be fired.
  307. // @param {Object} data Object with `type: content` pairs used as data transfer data in the fired paste event.
  308. function firePasteEvent( editor, data ) {
  309. editor.editing.view.document.fire( 'paste', {
  310. dataTransfer: createDataTransfer( data ),
  311. preventDefault() {}
  312. } );
  313. }