File Coverage

blib/lib/Locale/Maketext/Test.pm
Criterion Covered Total %
statement 146 160 91.2
branch 47 68 69.1
condition 12 20 60.0
subroutine 24 24 100.0
pod 2 2 100.0
total 231 274 84.3


line stmt bran cond sub pod time code
1             package Locale::Maketext::Test;
2              
3 7     7   130219 use 5.014;
  7         16  
4 7     7   22 use strict;
  7         8  
  7         105  
5 7     7   16 use warnings;
  7         11  
  7         128  
6 7     7   3286 use utf8;
  7         54  
  7         26  
7              
8 7     7   2922 use Try::Tiny;
  7         12114  
  7         275  
9 7     7   32 use File::Spec;
  7         6  
  7         105  
10 7     7   2638 use Test::MockModule;
  7         25158  
  7         158  
11 7     7   2711 use Locale::Maketext::ManyPluralForms;
  7         80230  
  7         40  
12              
13             =encoding UTF-8
14              
15             =head1 NAME
16              
17             Locale::Maketext::Test
18              
19             =head1 VERSION
20              
21             Version 0.04
22              
23             =cut
24              
25             our $VERSION = '0.04';
26              
27             =head1 SYNOPSIS
28              
29             use Locale::Maketext::Test;
30              
31             my $foo = Locale::Maketext::Test->new(directory => '/tmp/locales'); # it will look for files like id.po, ru.po
32              
33             ### optional parameters
34             # languages => ['en', 'de'] - to test specific languages in directory, else it will pick all po files in directory
35             # ideally these languages should be as per https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes format
36             # debug => 1 - if you want to check warnings add debug flag else it will output errors only
37             # auto => 1 set only when you want to fallback in case a key is missing from lexicons
38              
39             # start test
40             my $response = $foo->testlocales();
41              
42             # no errors or warnings if
43             $response->{status} eq 1;
44              
45             # something is wrong when
46             $response->{status} eq 0;
47              
48             # check for errors and warnings in case status is 0
49             $response->{errors} = {id => [error1, error2], ru => [error1, error2]};
50             # warnings are only present when debug is set to 1
51             $response->{warnings} = {id => [warn1, warn2], ru => [warn1, warn2]};
52              
53             =head1 DESCRIPTION
54              
55             This reads all message ids from the specified PO files and tries to
56             translate them into the destination language. PO files can be specified either
57             as file name (extension .po) or by providing the language. In the latter case
58             the PO file is found in the directory given by the directory option.
59              
60             =head2 TYPES OF ERRORS FOUND
61              
62             =head3 unknown %func() calls
63              
64             Translations can contain function calls in the form of %func(parameters).
65             These functions must be defined in our code. Sometimes translators try
66             to translate the function name which then calls an undefined function.
67              
68             =head3 incorrect number of %plural() parameters
69              
70             Different languages have different numbers of plural forms.
71             Some, like Malay, don't have any plural forms. Some, like English or French,
72             have just 2 forms, singular and one plural. Others like Arabic or Russian have
73             more forms. Whenever a translator uses the %plural() function, he must specify
74             the correct number of plural forms as parameters.
75              
76             =head3 incorrect usage of %d in %plural() parameters
77              
78             In some languages, like English or German, singular is applicable only to the
79             quantity of 1. That means the German translator could come up for instance
80             with the following valid %plural call:
81              
82             %plural(%5,ein Stein,%d Steine)
83              
84             In other languages, like French or Russian, this would be an error. French uses
85             singular also for 0 quantities. So, if the French translator calls:
86              
87             %plural(%5,une porte,%d portes)
88              
89             and in the actual call the quantity of 0 is passed the output is still "une porte".
90             In Russian the problem is even more critical because singular is used for instance
91             also for the quantity of 121.
92              
93             Thus, this test checks if a) the target language is similar to English in having only
94             2 plural forms, singular and one plural, and in applying singular only to the quantity
95             of 1. If both of these conditions are met %plural calls like the above are allowed.
96             Otherwise, if at least one of the parameters passed to %plural contains a %d,
97             all of the parameters must contain the %d as well.
98              
99             That means the following 2 %plural calls are allowed in Russian:
100              
101             %plural(%3,%d книга,%d книги,%d книг)
102             %3 %plural(%3,книга,книги,книг)
103              
104             while this is forbidden:
105              
106             %plural(%3,одна книга,%d книги,%d книг)
107              
108             =head1 SUBROUTINES/METHODS
109              
110             =head2 debug
111              
112             set this if you need to check warnings along with errors
113              
114             =cut
115              
116 7     7   3485 use Moose;
  7         2012465  
  7         47  
117 7     7   35536 use namespace::autoclean;
  7         36900  
  7         20  
118              
119             has debug => (
120             is => 'ro',
121             isa => 'Bool',
122             default => 0
123             );
124              
125             =head2 directory
126              
127             directory where locales files are located
128              
129             =cut
130              
131             has directory => (
132             is => 'ro',
133             isa => 'Str',
134             required => 1
135             );
136              
137             =head2 languages
138              
139             language array, set this if you want to test specific language only in specified directory
140              
141             =cut
142              
143             has languages => (
144             is => 'rw',
145             isa => 'ArrayRef[Str]',
146             default => sub { [] });
147              
148             =head2 auto
149              
150             flag to fallback when a key is missing from lexicons
151              
152             # if this is not set then maketext will output errors if
153             # translations is marked as fuzzy or is missing
154             # read more about it here https://metacpan.org/pod/Locale::Maketext::Lexicon
155             Locale::Maketext::Lexicon->import({ _auto => 1 })
156              
157             =cut
158              
159             has auto => (
160             is => 'ro',
161             isa => 'Bool',
162             default => 0
163             );
164              
165             has _status => (
166             is => 'rw',
167             isa => 'HashRef',
168             lazy => 1,
169             init_arg => undef,
170             default => sub {
171             {
172             status => 1,
173             errors => {},
174             warnings => {}};
175             });
176              
177             =head2 BUILD
178              
179             =cut
180              
181             sub BUILD {
182 6     6 1 8 my $self = shift;
183              
184 6 100       8 unless (scalar @{$self->languages}) {
  6         197  
185 1         5 my @lang = ();
186 1 50       29 if (opendir my $dh, $self->directory) {
187 1         14 while (readdir $dh) {
188 5 100       17 if (my ($x) = ($_ =~ /^(\w+)\.po$/)) {
189 3         8 push @lang, $x;
190             }
191             }
192 1         5 @lang = sort @lang;
193             }
194 1         27 $self->languages(\@lang);
195             }
196              
197             Locale::Maketext::ManyPluralForms->import({
198 6         188 '_decode' => 1,
199             '_auto' => $self->auto,
200             '*' => ['Gettext' => File::Spec->rel2abs($self->directory) . '/*.po']});
201             }
202              
203             =head2 testlocales
204              
205             test po files in directory specified
206              
207             =cut
208              
209             sub testlocales {
210 6     6 1 76 my $self = shift;
211              
212 6         9 foreach my $lang (@{$self->languages}) {
  6         156  
213 8         652 my $po = $self->_get_po($lang);
214 7         17 my $lg = $po->{header}->{language};
215 7         82 my $hnd = Locale::Maketext::ManyPluralForms->get_handle($lg);
216 7         11240 $hnd->plural(1, 'test %d');
217              
218 7         855 my $plural_sub = $hnd->{_plural};
219              
220 7         11 my $nplurals = 2; # default
221 7 50       72 $nplurals = $1 if $po->{header}->{'plural-forms'} =~ /\bnplurals=(\d+);/;
222 7         7 my @plural;
223              
224 7   66     60 for (my ($i, $j) = (0, $nplurals); $i < 10000 && $j > 0; $i++) {
225 13         207 my $pos = $plural_sub->($i);
226 13 50       56 unless (defined $plural[$pos]) {
227 13         15 $plural[$pos] = $i;
228 13         817 $j--;
229             }
230             }
231              
232             # $lang_plural_is_like_english==1 means the language has exactly 2 plural forms
233             # and singular is applied only to the quantity of 1. That means something like
234             # %plural(%d,ein Stern,%d Sterne) is allowed. In French for instance, singular is
235             # also applied to the quantity of 0. In that case the singular form should also
236             # contain a %d sequence.
237 7         13 my $lang_plural_is_like_english = ($nplurals == 2);
238 7 100       17 if ($lang_plural_is_like_english) {
239 4         15 for (my $i = 0; $i <= 100_000; $i++) {
240 400004 100       1423746 next if $i == 1;
241 400000 50       5623272 if ($plural_sub->($i) == 0) {
242 0         0 $lang_plural_is_like_english = 0;
243 0         0 last;
244             }
245             }
246             }
247              
248 7         27 my $ln;
249              
250 7         118 $plural_sub = $hnd->can('plural');
251 7         79 my $mock = Test::MockModule->new(ref($hnd), no_auto => 1);
252             $mock->mock(
253             plural => sub {
254             # The plural call should provide exactly the number of forms required by the language
255 1 50   1   232 push @{$self->_status->{errors}->{$lg}},
  1         24  
256 1         5 $self->_format_message($ln, "\%plural() requires $nplurals parameters for this language (provided: @{[@_ - 2]})")
257             unless @_ == $nplurals + 2;
258              
259             # %plural() can be used like
260             #
261             # %plural(%3,word,words)
262             #
263             # or like
264             #
265             # %plural(%3,%d word,%d words)
266             #
267             # In the first case we are only looking for the correct plural form
268             # providing the actual quantity elsewhere.
269             #
270             # The code below checks that either all parameters of the current call contain %d
271             # or none of them. That means something like %plural(%15,one word,%d words) is an
272             # error as singular is in many languages also applied to other quantities than 1.
273              
274 1         2 my $found_percent_d = 0;
275 1         1 my @no_percent_d;
276 1         3 for (my $i = 2; $i < @_; $i++) {
277 2 50       5 if ($_[$i] =~ /%d/) {
278 2         5 $found_percent_d++;
279             } else {
280             # $i==2 means it's the singular parameter. This one is allowed to not contain
281             # %d if the language is like English
282 0 0 0     0 push @no_percent_d, $i - 1 unless ($i == 2 and $lang_plural_is_like_english);
283             }
284             }
285 1 50       2 if ($found_percent_d) {
286 1 50       4 if (@no_percent_d > 1) {
    50          
287 0         0 my $s = join(', ', @no_percent_d[0 .. $#no_percent_d - 1]) . ' and ' . $no_percent_d[-1];
288 0         0 push @{$self->_status->{errors}->{$lg}}, $self->_format_message($ln, "\%plural() parameters $s miss %d");
  0         0  
289             } elsif (@no_percent_d == 1) {
290 0         0 push @{$self->_status->{errors}->{$lg}}, $self->_format_message($ln, "\%plural() parameter $no_percent_d[0] misses %d");
  0         0  
291             }
292             }
293              
294 1         4 goto $plural_sub;
295 7         1242 });
296              
297 7         455 for my $test (@{$po->{ids}}) {
  7         46  
298 21         1427 $ln = $test->[3];
299 21         26 my $i = 0;
300 21         17 my $j = 0;
301             my @param = map {
302 29         46 $j++;
303 29 100 100     352 push @{$self->_status->{warnings}->{$lg}}, $self->_format_message($ln, "unused parameter \%$j") if (not defined $_ and $self->debug);
  2         45  
304 29 100 100     103 defined $_ && $_ eq 'text' ? 'text' . $i++ : 1;
305 21         16 } @{$test->[1]};
  21         46  
306             try {
307 21     21   613 local $SIG{__WARN__} = sub { die $_[0] };
  0         0  
308 21         134 $hnd->maketext($test->[0], @param);
309             }
310             catch {
311 6 50   6   1174 if (/Can't locate object method "([^"]+)" via package/) {
312 0         0 push @{$self->_status->{errors}->{$lg}}, $self->_format_message($ln, "Unknown directive \%$1()");
  0         0  
313             } else {
314 6         9 push @{$self->_status->{errors}->{$lg}}, $self->_format_message($ln, "Unexpected error:\n$_");
  6         196  
315             }
316 21         960 };
317             }
318             }
319              
320 5         1991 return $self->_status;
321             }
322              
323             =pod
324              
325             This returns hash with status, errors and warnings
326              
327             {
328             status => 1/0, # 1 is success, 0 failure
329             errors => { id => [error1, error2], ru => [error1, error2] },
330             warnings => { id => [warn1, warn2] }
331             }
332              
333             =cut
334              
335             sub _cstring {
336 49     49   137 my %map = (
337             'a' => "\007",
338             'b' => "\010",
339             't' => "\011",
340             'n' => "\012",
341             'v' => "\013",
342             'f' => "\014",
343             'r' => "\015",
344             );
345 49         174 return $_[0] =~ s/
346             \\
347             (?:
348             ([0-7]{1,3})
349             |
350             x([0-9a-fA-F]{1,2})
351             |
352             ([\\'"?abfvntr])
353             )
354 84 50 33     387 /$1 ? chr(oct($1)) : $2 ? chr(hex($2)) : ($map{$3} || $3)/regx;
    50          
355             }
356              
357             sub _bstring {
358 21     21   17 my @params;
359 21         138 return $_[0] =~ s!
360             (?> # matches %func(%N,parameters...)
361             %
362             (?<func>\w+)
363             \(
364             %
365             (?<p0>[0-9]+)
366             (?<prest>[^\)]*)
367             \)
368             )
369             |
370             (?> # matches %func(parameters)
371             %
372             (?<simplefunc>\w+)
373             \(
374             (?<simpleparm>[^\)]*)
375             \)
376             )
377             | # matches %N
378             %
379             (?<simple>[0-9]+)
380             | # [, ] and ~ should be escaped as ~[, ~] and ~~
381             (?<esc>[\[\]~])
382             !
383 7 50   7   10605 if ($+{esc}) {
  7 50       1948  
  7         5033  
  17         123  
384 0         0 "~$+{esc}";
385             } elsif ($+{simplefunc}) {
386 0         0 "[$+{simplefunc},$+{simpleparm}]";
387             } else {
388 17 100       77 my $pos = ($+{func} ? $+{p0} : $+{simple}) - 1;
389 17 100 66     107 $params[$pos] = $+{func} && $+{func} eq 'plural' ? 'plural' : ($params[$pos] // 'text');
      50        
390 17 100       131 $+{func} ? "[$+{func},_$+{p0}$+{prest}]" : "[_$+{simple}]";
391             }
392             !regx, \@params;
393             }
394              
395             {
396             my @stack;
397              
398             sub _nextline {
399 242 100   242   374 return pop @stack if @stack;
400 193         545 return scalar readline $_[0];
401             }
402              
403             sub _unread {
404 49     49   60 push @stack, @_;
405             }
406             }
407              
408             sub _get_trans {
409 28     28   27 my $f = shift;
410              
411 28         38 while (defined(my $l = _nextline($f))) {
412 28 50       96 if ($l =~ /^\s*msgstr\s*"(.*)"/) {
413 28         33 my $line = $1;
414 28         37 while (defined($l = _nextline($f))) {
415 105 100       219 if ($l =~ /^\s*"(.*)"/) {
416 84         153 $line .= $1;
417             } else {
418 21         25 _unread($l);
419 21         33 return _cstring($line);
420             }
421             }
422 7         19 return _cstring($line);
423             }
424             }
425             }
426              
427             sub _get_po {
428 8     8   14 my ($self, $lang, $header_only) = @_;
429              
430 8 50       27 unless ($lang =~ /\.po$/) {
431 8         210 $lang = $self->directory . '/' . $lang . '.po';
432             }
433              
434 8         14 my (%header, @ids, $ln);
435 8         9 my $first = 1;
436              
437 8 100   6   285 open my $f, '<:encoding(UTF-8)', $lang or die "Cannot open $lang: $!\n";
  6         33  
  6         6  
  6         39  
438             READ:
439 7         38399 while (defined(my $l = _nextline($f))) {
440 67 100       325 if ($l =~ /^\s*msgid\s*"(.*)"/) {
441 28         63 my $line = $1;
442 28         34 $ln = $.;
443 28         36 while (defined($l = _nextline($f))) {
444 28 50       117 if ($l =~ /^\s*"(.*)"/) {
445 0         0 $line .= $1;
446             } else {
447 28         46 _unread($l);
448 28 100       71 if ($first) {
    50          
449 7         11 undef $first;
450 7         20 %header = map { split /\s*:\s*/, lc($_), 2 } split /\n/, _get_trans($f);
  84         363  
451 7 50       39 last READ if $header_only;
452             } elsif (length $line) {
453 21         30 push @ids, [_bstring(_cstring($line)), _get_trans($f), $ln];
454             }
455 28         68 last;
456             }
457             }
458             }
459             }
460              
461             return {
462             header => \%header,
463             ids => \@ids,
464             lang => $header{language},
465 7         134 file => $lang,
466             };
467             }
468              
469             sub _format_message {
470 9     9   11 my ($self, $line, $message) = @_;
471 9         210 $self->_status->{status} = 0;
472 9         81 return "(line=$line): $message";
473             }
474              
475             __PACKAGE__->meta->make_immutable;
476              
477             =head1 AUTHOR
478              
479             Binary.com, C<< <binary at cpan.org> >>
480              
481             =head1 BUGS
482              
483             Please report any bugs or feature requests to C<bug-locale-maketext-test at rt.cpan.org>, or through
484             the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Locale-Maketext-Test>. I will be notified, and then you'll
485             automatically be notified of progress on your bug as I make changes.
486              
487              
488              
489              
490             =head1 SUPPORT
491              
492             You can find documentation for this module with the perldoc command.
493              
494             perldoc Locale::Maketext::Test
495              
496              
497             You can also look for information at:
498              
499             =over 4
500              
501             =item * RT: CPAN's request tracker (report bugs here)
502              
503             L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Locale-Maketext-Test>
504              
505             =item * AnnoCPAN: Annotated CPAN documentation
506              
507             L<http://annocpan.org/dist/Locale-Maketext-Test>
508              
509             =item * CPAN Ratings
510              
511             L<http://cpanratings.perl.org/d/Locale-Maketext-Test>
512              
513             =item * Search CPAN
514              
515             L<http://search.cpan.org/dist/Locale-Maketext-Test/>
516              
517             =back
518              
519              
520             =head1 ACKNOWLEDGEMENTS
521              
522              
523             =head1 LICENSE AND COPYRIGHT
524              
525             Copyright 2016 Binary.com.
526              
527             This program is free software; you can redistribute it and/or modify it
528             under the terms of the the Artistic License (2.0). You may obtain a
529             copy of the full license at:
530              
531             L<http://www.perlfoundation.org/artistic_license_2_0>
532              
533             Any use, modification, and distribution of the Standard or Modified
534             Versions is governed by this Artistic License. By using, modifying or
535             distributing the Package, you accept this license. Do not use, modify,
536             or distribute the Package, if you do not accept this license.
537              
538             If your Modified Version has been derived from a Modified Version made
539             by someone other than you, you are nevertheless required to ensure that
540             your Modified Version complies with the requirements of this license.
541              
542             This license does not grant you the right to use any trademark, service
543             mark, tradename, or logo of the Copyright Holder.
544              
545             This license includes the non-exclusive, worldwide, free-of-charge
546             patent license to make, have made, use, offer to sell, sell, import and
547             otherwise transfer the Package with respect to any patent claims
548             licensable by the Copyright Holder that are necessarily infringed by the
549             Package. If you institute patent litigation (including a cross-claim or
550             counterclaim) against any party alleging that the Package constitutes
551             direct or contributory patent infringement, then this Artistic License
552             to you shall terminate on the date that such litigation is filed.
553              
554             Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
555             AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
556             THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
557             PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
558             YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
559             CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
560             CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
561             EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
562              
563              
564             =cut
565              
566             1; # End of Locale::Maketext::Test