utils.js 14 KB

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