Data/Fake/CPAN.pm untested

filter: Statementstmt 0.0% 0 / 108 Branchbran 0.0% 0 / 2 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 146 CC 2 SCAR 8.4
CC
2
Cov
0%
fake_package_names
6.0
fake_cpan_author
2.0
_package
2.0
CRAP 2.3
1 package Data::Fake::CPAN 0.027;
2 use v5.20.0;
3 use warnings;
4  
5 # ABSTRACT: a Data::Fake plugin for CPAN data and distributions
6  
7 # Back off, man, I'm a scientist.
8 use experimental qw(lexical_subs postderef signatures);
9  
10 #pod =head1 SYNOPSIS
11 #pod
12 #pod use Data::Fake qw(CPAN);
13 #pod
14 #pod my $dist = fake_cpan_distribution()->();
15 #pod
16 #pod my $archive = $dist->make_archive({ dir => '.' });
17 #pod say "Produced archive as $archive (cpan author: " . $dist->cpan_author . ")";
18 #pod say "- $_" for sort map {; $_->name } $dist->packages;
19 #pod
20 #pod This is a Data::Fake plugin for generating CPAN distributions. Right now, it
21 #pod can't be configured in any way, but future revisions might add some options.
22 #pod You can use this to generate libraries to test your CPAN-related tooling, to
23 #pod test L<PAUSE|https://pause.perl.org>. Make 10,000 and host your own competing
24 #pod CPAN. The possibilities are endless.
25 #pod
26 #pod All the C<fake_...> functions exported by Data::Fake::CPAN are exported by
27 #pod default, and you're meant to use them via C<use Data::Fake>. Like the rest of
28 #pod Data::Fake generators, they return subroutines that you must call to get the
29 #pod actual faked data.
30 #pod
31 #pod =cut
32  
33 use Data::Fake qw( Core Dates );
34 use List::Util qw(uniq);
35  
36 use Sub::Exporter -setup => {
37 groups => { default => [ '-all' ] },
38 exports => [ qw(
39 fake_cpan_author
40 fake_cpan_distribution
41 fake_license
42 fake_package_names
43 fake_prereqs
44 fake_version
45 ) ],
46 };
47  
48 #pod =func fake_cpan_author
49 #pod
50 #pod This generator generates objects representing CPAN authors. These methods are
51 #pod provided
52 #pod
53 #pod =for :list
54 #pod * given_name - a first name from Data::Fake::Names
55 #pod * surname - a surname from Data::Fake::Names
56 #pod * full_name - given name, space, surname
57 #pod * pauseid - an all caps PAUSE user id
58 #pod * email_address - an email address
59 #pod * name_and_email - a string in the form "full_name <email_address>"
60 #pod
61 #pod If you call this generator many times, you might get duplicated data, but the
62 #pod odds are not high.
63 #pod
64 #pod =cut
65  
66 sub fake_cpan_author {
67 sub { Module::Faker::Blaster::Author->new }
68 }
69  
70 #pod =func fake_cpan_distribution
71 #pod
72 #pod This creates an entire CPAN distribution, as a Module::Faker::Dist object. It
73 #pod will contain at least one package, and possibly several.
74 #pod
75 #pod =cut
76  
77 my sub _package ($name) {
78 state $config = {
79 layout => {
80 pkgword => fake_weighted(
81 [ package => 4 ],
82 [ class => 1 ],
83 [ role => 1 ],
84 )->(),
85 style => fake_pick(qw( statement block ))->(),
86 version => fake_pick(qw( our our-literal inline ))->(),
87 },
88 };
89  
90 return $name => $config;
91 }
92  
93 sub fake_cpan_distribution {
94 require Module::Faker::Dist;
95  
96 sub {
97 my @package_names = fake_package_names(fake_int(1,6)->())->();
98  
99 my $author = fake_cpan_author()->();
100  
101 my $ext = fake_weighted(
102 [ 'tar.gz' => 4 ],
103 [ zip => 1 ],
104 )->();
105  
106 my $dist = Module::Faker::Dist->from_struct({
107 name => ($package_names[0] =~ s/::/-/gr),
108 version => fake_version()->(),
109 authors => [ $author->name_and_email ],
110 cpan_author => $author->pauseid,
111 license => [ fake_license()->() ],
112 archive_ext => $ext,
113 packages => [ map {; _package($_) } sort @package_names ],
114 prereqs => fake_prereqs()->(),
115 });
116 }
117 }
118  
119 #pod =func fake_license
120 #pod
121 #pod This generator will spit out license values for a CPAN::Meta file, like
122 #pod C<perl_5> or C<openssl> or C<unknown>.
123 #pod
124 #pod =cut
125  
126 sub fake_license {
127 state @specific = qw(
128 agpl_3 apache_1_1 apache_2_0 artistic_1 artistic_2 bsd freebsd gfdl_1_2
129 gfdl_1_3 gpl_1 gpl_2 gpl_3 lgpl_2_1 lgpl_3_0 mit mozilla_1_0 mozilla_1_1
130 openssl perl_5 qpl_1_0 ssleay sun zlib
131 );
132  
133 state @general = qw( open_source restricted unrestricted unknown );
134  
135 fake_pick(@specific, @general);
136 }
137  
138 #pod =func fake_package_names
139 #pod
140 #pod my $generator = fake_package_names($n);
141 #pod
142 #pod The constructed generator will return I<n> package names. The first package
143 #pod name will be a prefix of all the rest of the package names.
144 #pod
145 #pod =cut
146  
147 my sub make_identifier ($str) {
148 my @bits = split /[^A-Za-z0-9_]/, $str;
149 join q{}, map {; ucfirst } @bits;
150 }
151  
152 sub fake_package_names ($n) {
153 return unless $n >= 1;
154  
155 sub {
156 my @base = map { make_identifier( _noun() ) } (1 .. fake_int(1,2)->());
157 my @names = join q{::}, @base;
158  
159 my @adjs = uniq map {; make_identifier( _adj() ) } (1 .. $n-1);
160 push @names, map {; join q{::}, $names[0], $_ } @adjs;
161  
162 return @names;
163 }
164 }
165  
166 #pod =func fake_prereqs
167 #pod
168 #pod This generator will produce a reference to a hash that can be used as the
169 #pod C<prereqs> entry in a CPAN::Meta file. Various type and phase combinations
170 #pod will be produced with unevenly distributed probabilities. All package names
171 #pod will be faked with C<fake_package_names>.
172 #pod
173 #pod =cut
174  
175 sub fake_prereqs {
176 sub {
177 my %prereqs;
178  
179 my $mk_phase = fake_weighted(
180 [ configure => 1 ],
181 [ runtime => 10 ],
182 [ build => 2 ],
183 [ test => 3 ],
184 [ develop => 2 ],
185 );
186  
187 my $mk_type = fake_weighted(
188 [ conflicts => 1 ],
189 [ recommends => 3 ],
190 [ requires => 15 ],
191 [ suggests => 1 ],
192 );
193  
194 for (1 .. fake_int(0, 20)->()) {
195 my $phase = $mk_phase->();
196 my $type = $mk_type->();
197  
198 my ($package) = fake_package_names(1)->();
199 $prereqs{$phase}{$type}{$package} = fake_version()->();
200 }
201  
202 return \%prereqs;
203 }
204 }
205  
206 package Module::Faker::Blaster::Author 0.027 {
207 use Moose;
208  
209 use Data::Fake::Names ();
210  
211 use v5.20.0;
212 # I collect spores, molds and fungus.
213 use experimental qw(lexical_subs postderef signatures);
214  
215 has given_name => (
216 is => 'ro',
217 default => sub { Data::Fake::Names::fake_first_name()->() },
218 );
219  
220 has surname => (
221 is => 'ro',
222 default => sub { Data::Fake::Names::fake_surname()->() },
223 );
224  
225 sub full_name ($self) {
226 join q{ }, $self->given_name, $self->surname;
227 }
228  
229 has pauseid => (
230 is => 'ro',
231 lazy => 1,
232 default => sub ($self) {
233 uc( substr($self->given_name, 0, 1) . substr($self->surname, 0, 7));
234 },
235 );
236  
237 has email_address => (
238 is => 'ro',
239 lazy => 1,
240 default => sub ($self) {
241 lc $self->pauseid . '@fakecpan.org';
242 },
243 );
244  
245 sub name_and_email ($self) {
246 sprintf "%s <%s>", $self->full_name, $self->email_address;
247 }
248  
249 no Moose;
250 }
251  
252 my @v_generators = (
253 sub {
254 # n.nnn
255 my $ver_x = int rand 10;
256 my $ver_y = int rand 1000;
257  
258 return sprintf '%d.%03d', $ver_x, $ver_y;
259 },
260 sub {
261 # YYYYMMDD.nnn
262 my $date = fake_past_datetime('%Y%m%d')->();
263 return sprintf '%d.%03d', $date, int rand 1000;
264 },
265 sub {
266 # x.y.z
267 return join q{.}, map {; int rand 20 } (1..3);
268 },
269 );
270  
271 sub fake_version {
272 fake_pick(@v_generators);
273 }
274  
275 my @ADJECTIVES = qw(
276 abandoned able absolute adorable adventurous academic acceptable acclaimed
277 accomplished accurate aching acidic acrobatic active actual adept admirable
278 admired adolescent adorable adored advanced afraid affectionate aged
279 aggravating aggressive agile agitated agonizing agreeable ajar alarmed
280 alarming alert alienated alive all altruistic amazing ambitious ample amused
281 amusing anchored ancient angelic angry anguished animated annual another
282 antique anxious any apprehensive appropriate apt arctic arid aromatic
283 artistic ashamed assured astonishing athletic attached attentive attractive
284 austere authentic authorized automatic avaricious average aware awesome
285 awful awkward babyish bad back baggy bare barren basic beautiful belated
286 beloved beneficial better best bewitched big big-hearted biodegradable
287 bite-sized bitter black black-and-white bland blank blaring bleak blind
288 blissful blond blue blushing bogus boiling bold bony boring bossy both
289 bouncy bountiful bowed brave breakable brief bright brilliant brisk broken
290 bronze brown bruised bubbly bulky bumpy buoyant burdensome burly bustling
291 busy buttery buzzing calculating calm candid canine capital carefree careful
292 careless caring cautious cavernous celebrated charming cheap cheerful cheery
293 chief chilly chubby circular classic clean clear clear-cut clever close
294 closed cloudy clueless clumsy cluttered coarse cold colorful colorless
295 colossal comfortable common compassionate competent complete complex
296 complicated composed concerned concrete confused conscious considerate
297 constant content conventional cooked cool cooperative coordinated corny
298 corrupt costly courageous courteous crafty crazy creamy creative creepy
299 criminal crisp critical crooked crowded cruel crushing cuddly cultivated
300 cultured cumbersome curly curvy cute cylindrical damaged damp dangerous
301 dapper daring darling dark dazzling dead deadly deafening dear dearest
302 decent decimal decisive deep defenseless defensive defiant deficient
303 definite definitive delayed delectable delicious delightful delirious
304 demanding dense dental dependable dependent descriptive deserted detailed
305 determined devoted different difficult digital diligent dim dimpled
306 dimwitted direct disastrous discrete disfigured disgusting disloyal dismal
307 distant downright dreary dirty disguised dishonest dismal distant distinct
308 distorted dizzy dopey doting double downright drab drafty dramatic dreary
309 droopy dry dual dull dutiful each eager earnest early easy easy-going
310 ecstatic edible educated elaborate elastic elated elderly electric elegant
311 elementary elliptical embarrassed embellished eminent emotional empty
312 enchanted enchanting energetic enlightened enormous enraged entire envious
313 equal equatorial essential esteemed ethical euphoric even evergreen
314 everlasting every evil exalted excellent exemplary exhausted excitable
315 excited exciting exotic expensive experienced expert extraneous extroverted
316 extra-large extra-small fabulous failing faint fair faithful fake false
317 familiar famous fancy fantastic far faraway far-flung far-off fast fat fatal
318 fatherly favorable favorite fearful fearless feisty feline female feminine
319 few fickle filthy fine finished firm first firsthand fitting fixed flaky
320 flamboyant flashy flat flawed flawless flickering flimsy flippant flowery
321 fluffy fluid flustered focused fond foolhardy foolish forceful forked formal
322 forsaken forthright fortunate fragrant frail frank frayed free French fresh
323 frequent friendly frightened frightening frigid frilly frizzy frivolous
324 front frosty frozen frugal fruitful full fumbling functional funny fussy
325 fuzzy gargantuan gaseous general generous gentle genuine giant giddy
326 gigantic gifted giving glamorous glaring glass gleaming gleeful glistening
327 glittering gloomy glorious glossy glum golden good good-natured gorgeous
328 graceful gracious grand grandiose granular grateful grave gray great greedy
329 green gregarious grim grimy gripping grizzled gross grotesque grouchy
330 grounded growing growling grown grubby gruesome grumpy guilty gullible gummy
331 hairy half handmade handsome handy happy happy-go-lucky hard hard-to-find
332 harmful harmless harmonious harsh hasty hateful haunting healthy heartfelt
333 hearty heavenly heavy hefty helpful helpless hidden hideous high high-level
334 hilarious hoarse hollow homely honest honorable honored hopeful horrible
335 hospitable hot huge humble humiliating humming humongous hungry hurtful
336 husky icky icy ideal idealistic identical idle idiotic idolized ignorant ill
337 illegal ill-fated ill-informed illiterate illustrious imaginary imaginative
338 immaculate immaterial immediate immense impassioned impeccable impartial
339 imperfect imperturbable impish impolite important impossible impractical
340 impressionable impressive improbable impure inborn incomparable incompatible
341 incomplete inconsequential incredible indelible inexperienced indolent
342 infamous infantile infatuated inferior infinite informal innocent insecure
343 insidious insignificant insistent instructive insubstantial intelligent
344 intent intentional interesting internal international intrepid ironclad
345 irresponsible irritating itchy jaded jagged jam-packed jaunty jealous
346 jittery joint jolly jovial joyful joyous jubilant judicious juicy jumbo
347 junior jumpy juvenile kaleidoscopic keen key kind kindhearted kindly klutzy
348 knobby knotty knowledgeable knowing known kooky kosher lame lanky large last
349 lasting late lavish lawful lazy leading lean leafy left legal legitimate
350 light lighthearted likable likely limited limp limping linear lined liquid
351 little live lively livid loathsome lone lonely long long-term loose lopsided
352 lost loud lovable lovely loving low loyal lucky lumbering luminous lumpy
353 lustrous luxurious mad made-up magnificent majestic major male mammoth
354 married marvelous masculine massive mature meager mealy mean measly meaty
355 medical mediocre medium meek mellow melodic memorable menacing merry messy
356 metallic mild milky mindless miniature minor minty miserable miserly
357 misguided misty mixed modern modest moist monstrous monthly monumental moral
358 mortified motherly motionless mountainous muddy muffled multicolored mundane
359 murky mushy musty muted mysterious naive narrow nasty natural naughty
360 nautical near neat necessary needy negative neglected negligible neighboring
361 nervous new next nice nifty nimble nippy nocturnal noisy nonstop normal
362 notable noted noteworthy novel noxious numb nutritious nutty obedient obese
363 oblong oily oblong obvious occasional odd oddball offbeat offensive official
364 old old-fashioned only open optimal optimistic opulent orange orderly
365 organic ornate ornery ordinary original other our outlying outgoing
366 outlandish outrageous outstanding oval overcooked overdue overjoyed
367 overlooked palatable pale paltry parallel parched partial passionate past
368 pastel peaceful peppery perfect perfumed periodic perky personal pertinent
369 pesky pessimistic petty phony physical piercing pink pitiful plain plaintive
370 plastic playful pleasant pleased pleasing plump plush polished polite
371 political pointed pointless poised poor popular portly posh positive
372 possible potable powerful powerless practical precious present prestigious
373 pretty precious previous pricey prickly primary prime pristine private prize
374 probable productive profitable profuse proper proud prudent punctual pungent
375 puny pure purple pushy putrid puzzled puzzling quaint qualified quarrelsome
376 quarterly queasy querulous questionable quick quick-witted quiet
377 quintessential quirky quixotic quizzical radiant ragged rapid rare rash raw
378 recent reckless rectangular ready real realistic reasonable red reflecting
379 regal regular reliable relieved remarkable remorseful remote repentant
380 required respectful responsible repulsive revolving rewarding rich rigid
381 right ringed ripe roasted robust rosy rotating rotten rough round rowdy
382 royal rubbery rundown ruddy rude runny rural rusty sad safe salty same sandy
383 sane sarcastic sardonic satisfied scaly scarce scared scary scented
384 scholarly scientific scornful scratchy scrawny second secondary second-hand
385 secret self-assured self-reliant selfish sentimental separate serene serious
386 serpentine several severe shabby shadowy shady shallow shameful shameless
387 sharp shimmering shiny shocked shocking shoddy short short-term showy shrill
388 shy sick silent silky silly silver similar simple simplistic sinful single
389 sizzling skeletal skinny sleepy slight slim slimy slippery slow slushy small
390 smart smoggy smooth smug snappy snarling sneaky sniveling snoopy sociable
391 soft soggy solid somber some spherical sophisticated sore sorrowful soulful
392 soupy sour Spanish sparkling sparse specific spectacular speedy spicy spiffy
393 spirited spiteful splendid spotless spotted spry square squeaky squiggly
394 stable staid stained stale standard starchy stark starry steep sticky stiff
395 stimulating stingy stormy straight strange steel strict strident striking
396 striped strong studious stunning stupendous stupid sturdy stylish subdued
397 submissive substantial subtle suburban sudden sugary sunny super superb
398 superficial superior supportive sure-footed surprised suspicious svelte
399 sweaty sweet sweltering swift sympathetic tall talkative tame tan tangible
400 tart tasty tattered taut tedious teeming tempting tender tense tepid
401 terrible terrific testy thankful that these thick thin third thirsty this
402 thorough thorny those thoughtful threadbare thrifty thunderous tidy tight
403 timely tinted tiny tired torn total tough traumatic treasured tremendous
404 tragic trained tremendous triangular tricky trifling trim trivial troubled
405 true trusting trustworthy trusty truthful tubby turbulent twin ugly ultimate
406 unacceptable unaware uncomfortable uncommon unconscious understated
407 unequaled uneven unfinished unfit unfolded unfortunate unhappy unhealthy
408 uniform unimportant unique united unkempt unknown unlawful unlined unlucky
409 unnatural unpleasant unrealistic unripe unruly unselfish unsightly unsteady
410 unsung untidy untimely untried untrue unused unusual unwelcome unwieldy
411 unwilling unwitting unwritten upbeat upright upset urban usable used useful
412 useless utilized utter vacant vague vain valid valuable vapid variable vast
413 velvety venerated vengeful verifiable vibrant vicious victorious vigilant
414 vigorous villainous violet violent virtual virtuous visible vital vivacious
415 vivid voluminous wan warlike warm warmhearted warped wary wasteful watchful
416 waterlogged watery wavy wealthy weak weary webbed wee weekly weepy weighty
417 weird welcome well-documented well-groomed well-informed well-lit well-made
418 well-off well-to-do well-worn wet which whimsical whirlwind whispered white
419 whole whopping wicked wide wide-eyed wiggly wild willing wilted winding
420 windy winged wiry wise witty wobbly woeful wonderful wooden woozy wordy
421 worldly worn worried worrisome worse worst worthless worthwhile worthy
422 wrathful wretched writhing wrong wry yawning yearly yellow yellowish young
423 youthful yummy zany zealous zesty
424 );
425  
426 my @NOUNS = qw(
427 ability accident activity actor ad addition administration advertising
428 advice agency agreement airport alcohol analysis anxiety apartment
429 appearance application appointment area argument army arrival art article
430 aspect assistance association assumption atmosphere attention attitude
431 audience awareness baseball basis basket bath bird blood bonus boyfriend
432 bread breath buyer cabinet camera cancer candidate category cell chapter
433 charity chemistry chest child childhood chocolate church cigarette city
434 classroom climate clothes coffee collection college combination committee
435 communication community comparison competition complaint computer concept
436 conclusion confusion connection construction context contract contribution
437 control conversation cookie country county courage cousin criticism currency
438 customer dad data database dealer death debt decision definition delivery
439 department depression depth description desk development device difference
440 difficulty dinner direction director disaster discussion disease disk
441 distribution drama drawer drawing driver economics editor education
442 efficiency effort election elevator emotion emphasis employee employer
443 employment energy engine engineering entertainment enthusiasm entry
444 environment equipment error establishment estate event exam examination
445 excitement explanation expression extent fact failure family farmer feedback
446 finding fishing flight food football foundation freedom garbage gate girl
447 goal government grandmother grocery growth guest guidance guitar hair hall
448 health hearing heart height highway historian history homework honey
449 hospital hotel housing idea imagination importance impression improvement
450 income independence industry inflation information initiative injury insect
451 inspection inspector instance instruction insurance interaction internet
452 introduction investment judgment king knowledge lab ladder lake language law
453 leader leadership length library literature location loss love magazine
454 maintenance mall management manager manufacturer map marketing marriage math
455 meal meaning measurement meat media medicine member membership memory menu
456 message method mixture mode mom moment month mood movie mud music nation
457 nature news newspaper night office operation opinion opportunity orange
458 organization outcome oven owner painting paper passion patience payment
459 penalty people percentage perception performance permission person
460 personality perspective philosophy phone photo physics piano pie player poem
461 poetry police policy politics population possession possibility potato power
462 preference preparation presence presentation president priority problem
463 procedure product profession professor promotion property proposal
464 protection psychology quality quantity queen ratio reaction reading reality
465 reception recipe recommendation recording reflection refrigerator region
466 relation relationship replacement republic requirement resolution resource
467 response responsibility restaurant revenue revolution river road role safety
468 salad sample satisfaction scene science secretary sector security selection
469 series session setting shopping signature significance singer sister
470 situation skill society software solution son song soup speech statement
471 steak storage story strategy student studio success suggestion supermarket
472 system tea teacher teaching technology television temperature tennis tension
473 thanks theory thing thought tongue tooth topic town tradition transportation
474 truth two understanding union unit university user variation variety vehicle
475 version video village virus volume warning way weakness wealth wedding week
476 wife winner woman wood worker world writer writing year
477 );
478  
479 sub _noun { return $NOUNS[ rand @NOUNS ] }
480 sub _adj { return $ADJECTIVES[ rand @ADJECTIVES ] }
481  
482 1;
483  
484 __END__