8
0

utils.js 14 KB

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