View Javadoc

1   package org.apache.maven.wagon;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import org.apache.log4j.Logger;
23  import org.apache.maven.wagon.authentication.AuthenticationException;
24  import org.apache.maven.wagon.authentication.AuthenticationInfo;
25  import org.apache.maven.wagon.authorization.AuthorizationException;
26  import org.apache.maven.wagon.events.TransferEvent;
27  import org.apache.maven.wagon.events.TransferListener;
28  import org.apache.maven.wagon.observers.ChecksumObserver;
29  import org.apache.maven.wagon.observers.Debug;
30  import org.apache.maven.wagon.repository.Repository;
31  import org.apache.maven.wagon.repository.RepositoryPermissions;
32  import org.apache.maven.wagon.resource.Resource;
33  import org.codehaus.plexus.PlexusTestCase;
34  import org.codehaus.plexus.util.FileUtils;
35  import org.easymock.AbstractMatcher;
36  import org.easymock.MockControl;
37  
38  import java.io.File;
39  import java.io.IOException;
40  import java.security.NoSuchAlgorithmException;
41  import java.text.SimpleDateFormat;
42  import java.util.ArrayList;
43  import java.util.Iterator;
44  import java.util.List;
45  
46  /**
47   * @author <a href="mailto:jason@maven.org">Jason van Zyl</a>
48   * @version $Id: WagonTestCase.java 1173679 2011-09-21 14:32:35Z olamy $
49   */
50  public abstract class WagonTestCase
51      extends PlexusTestCase
52  {
53      protected static Logger logger = Logger.getLogger( WagonTestCase.class );
54  
55  
56      static final class ProgressArgumentMatcher
57          extends AbstractMatcher
58      {
59          private int size;
60  
61          protected boolean argumentMatches( Object expected, Object actual )
62          {
63              if ( actual instanceof byte[] )
64              {
65                  return true;
66              }
67              if ( actual instanceof Integer )
68              {
69                  size += ( (Integer) actual ).intValue();
70                  return true;
71              }
72              return super.argumentMatches( expected, actual );
73          }
74  
75          public int getSize()
76          {
77              return size;
78          }
79      }
80  
81      protected static String POM = "pom.xml";
82  
83      protected Repository localRepository;
84  
85      protected Repository testRepository;
86  
87      protected String localRepositoryPath;
88  
89      protected File sourceFile;
90  
91      protected File destFile;
92  
93      protected String resource;
94  
95      protected File artifactSourceFile;
96  
97      protected File artifactDestFile;
98  
99      protected ChecksumObserver checksumObserver;
100 
101     protected TransferListener mockTransferListener;
102 
103     protected MockControl mockTransferListenerControl;
104 
105     // ----------------------------------------------------------------------
106     // Constructors
107     // ----------------------------------------------------------------------
108 
109     protected void setUp()
110         throws Exception
111     {
112         checksumObserver = new ChecksumObserver();
113 
114         mockTransferListenerControl = MockControl.createControl( TransferListener.class );
115         mockTransferListener = (TransferListener) mockTransferListenerControl.getMock();
116 
117         super.setUp();
118     }
119 
120     // ----------------------------------------------------------------------
121     // Methods that should be provided by subclasses for proper testing
122     // ----------------------------------------------------------------------
123 
124     /**
125      * URL of the repository. For a complete test it should point to a non existing folder so we also check for the
126      * creation of new folders in the remote site. <p/> return the URL of the repository as specified by Wagon syntax
127      */
128     protected abstract String getTestRepositoryUrl()
129         throws IOException;
130 
131     /**
132      * Protocol id of the Wagon to use, eg. <code>scp</code>, <code>ftp</code>
133      *
134      * @return the protocol id
135      */
136     protected abstract String getProtocol();
137 
138     /**
139      * The number of the port which should get used to start the test server
140      *
141      * @return the port number for the test server
142      */
143     protected abstract int getTestRepositoryPort();
144 
145     // ----------------------------------------------------------------------
146     // 1. Create a local file repository which mimic a users local file
147     // Repository.
148     //
149     // 2. Create a test repository for the type of wagon we are testing. So,
150     // for example, for testing the file wagon we might have a test
151     // repository url of file://${basedir}/target/file-repository.
152     // ----------------------------------------------------------------------
153 
154     protected void setupRepositories()
155         throws Exception
156     {
157         resource = "test-resource";
158 
159         // ----------------------------------------------------------------------
160         // Create the test repository for the wagon we are testing.
161         // ----------------------------------------------------------------------
162 
163         testRepository = new Repository();
164 
165         testRepository.setUrl( getTestRepositoryUrl() );
166 
167         testRepository.setPermissions( getPermissions() );
168 
169         // ----------------------------------------------------------------------
170         // Create a test local repository.
171         // ----------------------------------------------------------------------
172 
173         localRepositoryPath = FileTestUtils.createDir( "local-repository" ).getPath();
174 
175         localRepository = createFileRepository( "file://" + localRepositoryPath );
176 
177         message( "Local repository: " + localRepository );
178 
179         File f = new File( localRepositoryPath );
180 
181         if ( !f.exists() )
182         {
183             f.mkdirs();
184         }
185     }
186 
187     protected void customizeContext()
188         throws Exception
189     {
190         getContainer().addContextValue( "test.repository", localRepositoryPath );
191     }
192 
193     protected void setupWagonTestingFixtures()
194         throws Exception
195     {
196     }
197 
198     protected void tearDownWagonTestingFixtures()
199         throws Exception
200     {
201     }
202 
203     // ----------------------------------------------------------------------
204     //
205     // ----------------------------------------------------------------------
206 
207     protected AuthenticationInfo getAuthInfo()
208     {
209         return new AuthenticationInfo();
210     }
211 
212     protected RepositoryPermissions getPermissions()
213     {
214         return new RepositoryPermissions();
215     }
216 
217     protected Wagon getWagon()
218         throws Exception
219     {
220         Wagon wagon = (Wagon) lookup( Wagon.ROLE, getProtocol() );
221 
222         Debug debug = new Debug();
223 
224         wagon.addSessionListener( debug );
225 
226         wagon.addTransferListener( debug );
227 
228         return wagon;
229     }
230 
231     protected void message( String message )
232     {
233         logger.info( message );
234     }
235 
236     // ----------------------------------------------------------------------
237     //
238     // ----------------------------------------------------------------------
239 
240     public void testWagon()
241         throws Exception
242     {
243         if ( supportsGetIfNewer() )
244         {
245             setupRepositories();
246 
247             setupWagonTestingFixtures();
248 
249             fileRoundTripTesting();
250 
251             tearDownWagonTestingFixtures();
252         }
253     }
254 
255     public void testWagonGetIfNewerIsNewer()
256         throws Exception
257     {
258         if ( supportsGetIfNewer() )
259         {
260             setupRepositories();
261             setupWagonTestingFixtures();
262             int expectedSize = putFile();
263             getIfNewer( getExpectedLastModifiedOnGet( testRepository, new Resource( resource ) ) + 30000, false,
264                         expectedSize );
265         }
266     }
267 
268     protected boolean supportsGetIfNewer()
269     {
270         return true;
271     }
272 
273     public void testWagonGetIfNewerIsOlder()
274         throws Exception
275     {
276         if ( supportsGetIfNewer() )
277         {
278             setupRepositories();
279             setupWagonTestingFixtures();
280             int expectedSize = putFile();
281             getIfNewer( new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2006-01-01" ).getTime(), true, expectedSize );
282         }
283     }
284 
285     public void testWagonGetIfNewerIsSame()
286         throws Exception
287     {
288         if ( supportsGetIfNewer() )
289         {
290             setupRepositories();
291             setupWagonTestingFixtures();
292             int expectedSize = putFile();
293             getIfNewer( getExpectedLastModifiedOnGet( testRepository, new Resource( resource ) ), false, expectedSize );
294         }
295     }
296 
297     private void getIfNewer( long timestamp, boolean expectedResult, int expectedSize )
298         throws Exception
299     {
300         Wagon wagon = getWagon();
301 
302         ProgressArgumentMatcher progressArgumentMatcher = setupGetIfNewerTest( wagon, expectedResult, expectedSize );
303 
304         connectWagon( wagon );
305 
306         boolean result = wagon.getIfNewer( this.resource, destFile, timestamp );
307         assertEquals( expectedResult, result );
308 
309         disconnectWagon( wagon );
310 
311         assertGetIfNewerTest( progressArgumentMatcher, expectedResult, expectedSize );
312 
313         tearDownWagonTestingFixtures();
314     }
315 
316     protected void assertGetIfNewerTest( ProgressArgumentMatcher progressArgumentMatcher, boolean expectedResult,
317                                          int expectedSize )
318         throws IOException
319     {
320         if ( expectedResult )
321         {
322             verifyMock( progressArgumentMatcher, expectedSize );
323 
324             assertNotNull( "check checksum is not null", checksumObserver.getActualChecksum() );
325 
326             assertEquals( "compare checksums", "6b144b7285ffd6b0bc8300da162120b9",
327                           checksumObserver.getActualChecksum() );
328 
329             // Now compare the contents of the artifact that was placed in
330             // the repository with the contents of the artifact that was
331             // retrieved from the repository.
332 
333             String sourceContent = FileUtils.fileRead( sourceFile );
334             String destContent = FileUtils.fileRead( destFile );
335             assertEquals( sourceContent, destContent );
336         }
337         else
338         {
339             mockTransferListenerControl.verify();
340 
341             mockTransferListenerControl.reset();
342 
343             assertNull( "check checksum is null", checksumObserver.getActualChecksum() );
344 
345             assertFalse( destFile.exists() );
346         }
347     }
348 
349     protected ProgressArgumentMatcher setupGetIfNewerTest( Wagon wagon, boolean expectedResult, int expectedSize )
350         throws NoSuchAlgorithmException, IOException
351     {
352         checksumObserver = new ChecksumObserver();
353 
354         destFile = FileTestUtils.createUniqueFile( getName(), getName() );
355         destFile.delete();
356         assertFalse( destFile.exists() );
357         destFile.deleteOnExit();
358 
359         ProgressArgumentMatcher progressArgumentMatcher = null;
360         if ( expectedResult )
361         {
362             progressArgumentMatcher = replaceMockForGet( wagon, expectedSize );
363         }
364         else
365         {
366             replaceMockForSkippedGetIfNewer( wagon, expectedSize );
367         }
368         return progressArgumentMatcher;
369     }
370 
371     private void replaceMockForSkippedGetIfNewer( Wagon wagon, int expectedSize )
372     {
373         Resource resource = new Resource( this.resource );
374         mockTransferListener.transferInitiated(
375             createTransferEvent( wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET,
376                                  destFile ) );
377         resource = new Resource( this.resource );
378         resource.setContentLength( getExpectedContentLengthOnGet( expectedSize ) );
379         resource.setLastModified( getExpectedLastModifiedOnGet( testRepository, resource ) );
380         // TODO: transfer skipped event?
381         // mockTransferListener.transferSkipped( createTransferEvent( wagon, resource, TransferEvent.TRANSFER_STARTED,
382         // TransferEvent.REQUEST_GET, destFile ) );
383 
384         mockTransferListener.debug( null );
385         mockTransferListenerControl.setMatcher( MockControl.ALWAYS_MATCHER );
386         mockTransferListenerControl.setVoidCallable( MockControl.ZERO_OR_MORE );
387 
388         mockTransferListenerControl.replay();
389     }
390 
391     public void testWagonPutDirectory()
392         throws Exception
393     {
394         setupRepositories();
395 
396         setupWagonTestingFixtures();
397 
398         Wagon wagon = getWagon();
399 
400         if ( wagon.supportsDirectoryCopy() )
401         {
402             sourceFile = new File( FileTestUtils.getTestOutputDir(), "directory-copy" );
403 
404             FileUtils.deleteDirectory( sourceFile );
405 
406             writeTestFile( "test-resource-1.txt" );
407             writeTestFile( "a/test-resource-2.txt" );
408             writeTestFile( "a/b/test-resource-3.txt" );
409             writeTestFile( "c/test-resource-4.txt" );
410             writeTestFile( "d/e/f/test-resource-5.txt" );
411 
412             wagon.connect( testRepository, getAuthInfo() );
413 
414             wagon.putDirectory( sourceFile, "directory-copy" );
415 
416             destFile = FileTestUtils.createUniqueFile( getName(), getName() );
417 
418             destFile.deleteOnExit();
419 
420             wagon.get( "directory-copy/test-resource-1.txt", destFile );
421             wagon.get( "directory-copy/a/test-resource-2.txt", destFile );
422             wagon.get( "directory-copy/a/b/test-resource-3.txt", destFile );
423             wagon.get( "directory-copy/c/test-resource-4.txt", destFile );
424             wagon.get( "directory-copy/d/e/f/test-resource-5.txt", destFile );
425 
426             wagon.disconnect();
427         }
428 
429         tearDownWagonTestingFixtures();
430     }
431 
432     /**
433      * Test for putting a directory with a destination that multiple directories deep, all of which haven't been
434      * created.
435      *
436      * @throws Exception
437      * @since 1.0-beta-2
438      */
439     public void testWagonPutDirectoryDeepDestination()
440         throws Exception
441     {
442         setupRepositories();
443 
444         setupWagonTestingFixtures();
445 
446         Wagon wagon = getWagon();
447 
448         if ( wagon.supportsDirectoryCopy() )
449         {
450             sourceFile = new File( FileTestUtils.getTestOutputDir(), "deep0/deep1/deep2" );
451 
452             FileUtils.deleteDirectory( sourceFile );
453 
454             writeTestFile( "test-resource-1.txt" );
455             writeTestFile( "a/test-resource-2.txt" );
456             writeTestFile( "a/b/test-resource-3.txt" );
457             writeTestFile( "c/test-resource-4.txt" );
458             writeTestFile( "d/e/f/test-resource-5.txt" );
459 
460             wagon.connect( testRepository, getAuthInfo() );
461 
462             wagon.putDirectory( sourceFile, "deep0/deep1/deep2" );
463 
464             destFile = FileTestUtils.createUniqueFile( getName(), getName() );
465 
466             destFile.deleteOnExit();
467 
468             wagon.get( "deep0/deep1/deep2/test-resource-1.txt", destFile );
469             wagon.get( "deep0/deep1/deep2/a/test-resource-2.txt", destFile );
470             wagon.get( "deep0/deep1/deep2/a/b/test-resource-3.txt", destFile );
471             wagon.get( "deep0/deep1/deep2/c/test-resource-4.txt", destFile );
472             wagon.get( "deep0/deep1/deep2/d/e/f/test-resource-5.txt", destFile );
473 
474             wagon.disconnect();
475         }
476 
477         tearDownWagonTestingFixtures();
478     }
479 
480     /**
481      * Test that when putting a directory that already exists new files get also copied
482      *
483      * @throws Exception
484      * @since 1.0-beta-1
485      */
486     public void testWagonPutDirectoryWhenDirectoryAlreadyExists()
487         throws Exception
488     {
489 
490         final String dirName = "directory-copy-existing";
491 
492         final String resourceToCreate = "test-resource-1.txt";
493 
494         final String[] resources = { "a/test-resource-2.txt", "a/b/test-resource-3.txt", "c/test-resource-4.txt" };
495 
496         setupRepositories();
497 
498         setupWagonTestingFixtures();
499 
500         Wagon wagon = getWagon();
501 
502         if ( wagon.supportsDirectoryCopy() )
503         {
504             sourceFile = new File( FileTestUtils.getTestOutputDir(), dirName );
505 
506             FileUtils.deleteDirectory( sourceFile );
507 
508             createDirectory( wagon, resourceToCreate, dirName );
509 
510             for ( int i = 0; i < resources.length; i++ )
511             {
512                 writeTestFile( resources[i] );
513             }
514 
515             wagon.connect( testRepository, getAuthInfo() );
516 
517             wagon.putDirectory( sourceFile, dirName );
518 
519             List resourceNames = new ArrayList( resources.length + 1 );
520 
521             resourceNames.add( dirName + "/" + resourceToCreate );
522             for ( int i = 0; i < resources.length; i++ )
523             {
524                 resourceNames.add( dirName + "/" + resources[i] );
525             }
526 
527             assertResourcesAreInRemoteSide( wagon, resourceNames );
528 
529             wagon.disconnect();
530         }
531 
532         tearDownWagonTestingFixtures();
533     }
534 
535     /**
536      * Test that when putting a directory that already exists new files get also copied and destination is "."
537      *
538      * @throws Exception
539      * @since 1.0-beta-1
540      */
541     public void testWagonPutDirectoryForDot()
542         throws Exception
543     {
544         final String resourceToCreate = "test-resource-1.txt";
545 
546         final String[] resources = { "a/test-resource-2.txt", "a/b/test-resource-3.txt", "c/test-resource-4.txt" };
547 
548         setupRepositories();
549 
550         setupWagonTestingFixtures();
551 
552         Wagon wagon = getWagon();
553 
554         if ( wagon.supportsDirectoryCopy() )
555         {
556             sourceFile = new File( FileTestUtils.getTestOutputDir(), "dot-repo" );
557 
558             FileUtils.deleteDirectory( sourceFile );
559 
560             createDirectory( wagon, resourceToCreate, "." );
561 
562             for ( int i = 0; i < resources.length; i++ )
563             {
564                 writeTestFile( resources[i] );
565             }
566 
567             wagon.connect( testRepository, getAuthInfo() );
568 
569             wagon.putDirectory( sourceFile, "." );
570 
571             List<String> resourceNames = new ArrayList<String>( resources.length + 1 );
572 
573             resourceNames.add( resourceToCreate );
574             for ( int i = 0; i < resources.length; i++ )
575             {
576                 resourceNames.add( resources[i] );
577             }
578 
579             assertResourcesAreInRemoteSide( wagon, resourceNames );
580 
581             wagon.disconnect();
582         }
583 
584         tearDownWagonTestingFixtures();
585     }
586 
587     /**
588      * Create a directory with a resource and check that the other ones don't exist
589      *
590      * @param wagon
591      * @param resourceToCreate name of the resource to be created
592      * @param dirName          directory name to create
593      * @throws Exception
594      */
595     protected void createDirectory( Wagon wagon, String resourceToCreate, String dirName )
596         throws Exception
597     {
598         writeTestFile( resourceToCreate );
599     }
600 
601     protected void assertResourcesAreInRemoteSide( Wagon wagon, List<String> resourceNames )
602         throws IOException, TransferFailedException, ResourceDoesNotExistException, AuthorizationException
603     {
604         Iterator<String> iter = resourceNames.iterator();
605         while ( iter.hasNext() )
606         {
607             String resourceName = iter.next();
608 
609             File destFile = FileTestUtils.createUniqueFile( getName(), resourceName );
610 
611             destFile.deleteOnExit();
612 
613             wagon.get( resourceName, destFile );
614         }
615     }
616 
617     /**
618      * Assert that a resource does not exist in the remote wagon system
619      *
620      * @param wagon        wagon to get the resource from
621      * @param resourceName name of the resource
622      * @throws IOException             if a temp file can't be created
623      * @throws AuthorizationException
624      * @throws TransferFailedException
625      * @since 1.0-beta-1
626      */
627     protected void assertNotExists( Wagon wagon, String resourceName )
628         throws IOException, TransferFailedException, AuthorizationException
629     {
630         File tmpFile = File.createTempFile( "wagon", null );
631         try
632         {
633             wagon.get( resourceName, tmpFile );
634             fail( "Resource exists: " + resourceName );
635         }
636         catch ( ResourceDoesNotExistException e )
637         {
638             // ok
639         }
640         finally
641         {
642             tmpFile.delete();
643         }
644     }
645 
646     private void writeTestFile( String child )
647         throws IOException
648     {
649         File dir = new File( sourceFile, child );
650         dir.getParentFile().mkdirs();
651         FileUtils.fileWrite( dir.getAbsolutePath(), child );
652     }
653 
654     public void testFailedGet()
655         throws Exception
656     {
657         setupRepositories();
658 
659         setupWagonTestingFixtures();
660 
661         message( "Getting test artifact from test repository " + testRepository );
662 
663         Wagon wagon = getWagon();
664 
665         wagon.addTransferListener( checksumObserver );
666 
667         wagon.connect( testRepository, getAuthInfo() );
668 
669         destFile = FileTestUtils.createUniqueFile( getName(), getName() );
670 
671         destFile.deleteOnExit();
672 
673         try
674         {
675             wagon.get( "fubar.txt", destFile );
676             fail( "File was found when it shouldn't have been" );
677         }
678         catch ( ResourceDoesNotExistException e )
679         {
680             // expected
681             assertTrue( true );
682         }
683         finally
684         {
685             wagon.removeTransferListener( checksumObserver );
686 
687             wagon.disconnect();
688 
689             tearDownWagonTestingFixtures();
690         }
691     }
692 
693     public void testFailedGetIfNewer()
694         throws Exception
695     {
696         if ( supportsGetIfNewer() )
697         {
698             setupRepositories();
699             setupWagonTestingFixtures();
700             message( "Getting test artifact from test repository " + testRepository );
701             Wagon wagon = getWagon();
702             wagon.addTransferListener( checksumObserver );
703             wagon.connect( testRepository, getAuthInfo() );
704             destFile = FileTestUtils.createUniqueFile( getName(), getName() );
705             destFile.deleteOnExit();
706             try
707             {
708                 wagon.getIfNewer( "fubar.txt", destFile, 0 );
709                 fail( "File was found when it shouldn't have been" );
710             }
711             catch ( ResourceDoesNotExistException e )
712             {
713                 // expected
714                 assertTrue( true );
715             }
716             finally
717             {
718                 wagon.removeTransferListener( checksumObserver );
719 
720                 wagon.disconnect();
721 
722                 tearDownWagonTestingFixtures();
723             }
724         }
725     }
726 
727     /**
728      * Test {@link Wagon#getFileList(String)}.
729      *
730      * @throws Exception
731      * @since 1.0-beta-2
732      */
733     public void testWagonGetFileList()
734         throws Exception
735     {
736         setupRepositories();
737 
738         setupWagonTestingFixtures();
739 
740         String dirName = "file-list";
741 
742         String filenames[] =
743             new String[]{ "test-resource.txt", "test-resource.pom", "test-resource b.txt", "more-resources.dat",
744                 ".index.txt" };
745 
746         for ( int i = 0; i < filenames.length; i++ )
747         {
748             putFile( dirName + "/" + filenames[i], dirName + "/" + filenames[i], filenames[i] + "\n" );
749         }
750 
751         Wagon wagon = getWagon();
752 
753         wagon.connect( testRepository, getAuthInfo() );
754 
755         List<String> list = wagon.getFileList( dirName );
756         assertNotNull( "file list should not be null.", list );
757         assertTrue( "file list should contain more items (actually contains '" + list + "').",
758                     list.size() >= filenames.length );
759 
760         for ( int i = 0; i < filenames.length; i++ )
761         {
762             assertTrue( "Filename '" + filenames[i] + "' should be in list.", list.contains( filenames[i] ) );
763         }
764 
765         // WAGON-250
766         list = wagon.getFileList( "" );
767         assertNotNull( "file list should not be null.", list );
768         assertTrue( "file list should contain items (actually contains '" + list + "').", !list.isEmpty() );
769         assertTrue( list.contains( "file-list/" ) );
770         assertFalse( list.contains( "file-list" ) );
771         assertFalse( list.contains( "." ) );
772         assertFalse( list.contains( ".." ) );
773         assertFalse( list.contains( "./" ) );
774         assertFalse( list.contains( "../" ) );
775 
776         wagon.disconnect();
777 
778         tearDownWagonTestingFixtures();
779     }
780 
781     /**
782      * Test {@link Wagon#getFileList(String)} when the directory does not exist.
783      *
784      * @throws Exception
785      * @since 1.0-beta-2
786      */
787     public void testWagonGetFileListWhenDirectoryDoesNotExist()
788         throws Exception
789     {
790         setupRepositories();
791 
792         setupWagonTestingFixtures();
793 
794         String dirName = "file-list-unexisting";
795 
796         Wagon wagon = getWagon();
797 
798         wagon.connect( testRepository, getAuthInfo() );
799 
800         try
801         {
802             wagon.getFileList( dirName );
803             fail( "getFileList on unexisting directory must throw ResourceDoesNotExistException" );
804         }
805         catch ( ResourceDoesNotExistException e )
806         {
807             // expected
808         }
809         finally
810         {
811             wagon.disconnect();
812 
813             tearDownWagonTestingFixtures();
814         }
815     }
816 
817     /**
818      * Test for an existing resource.
819      *
820      * @throws Exception
821      * @since 1.0-beta-2
822      */
823     public void testWagonResourceExists()
824         throws Exception
825     {
826         setupRepositories();
827 
828         setupWagonTestingFixtures();
829 
830         Wagon wagon = getWagon();
831 
832         putFile();
833 
834         wagon.connect( testRepository, getAuthInfo() );
835 
836         assertTrue( sourceFile.getName() + " does not exist", wagon.resourceExists( sourceFile.getName() ) );
837 
838         wagon.disconnect();
839 
840         tearDownWagonTestingFixtures();
841     }
842 
843     /**
844      * Test for an invalid resource.
845      *
846      * @throws Exception
847      * @since 1.0-beta-2
848      */
849     public void testWagonResourceNotExists()
850         throws Exception
851     {
852         setupRepositories();
853 
854         setupWagonTestingFixtures();
855 
856         Wagon wagon = getWagon();
857 
858         wagon.connect( testRepository, getAuthInfo() );
859 
860         assertFalse( wagon.resourceExists( "a/bad/resource/name/that/should/not/exist.txt" ) );
861 
862         wagon.disconnect();
863 
864         tearDownWagonTestingFixtures();
865     }
866 
867     // ----------------------------------------------------------------------
868     // File <--> File round trip testing
869     // ----------------------------------------------------------------------
870     // We are testing taking a file, our sourcefile, and placing it into the
871     // test repository that we have setup.
872     // ----------------------------------------------------------------------
873 
874     protected void putFile( String resourceName, String testFileName, String content )
875         throws Exception
876     {
877         sourceFile = new File( FileTestUtils.getTestOutputDir(), testFileName );
878         sourceFile.getParentFile().mkdirs();
879         FileUtils.fileWrite( sourceFile.getAbsolutePath(), content );
880 
881         Wagon wagon = getWagon();
882 
883         ProgressArgumentMatcher progressArgumentMatcher = replayMockForPut( resourceName, content, wagon );
884 
885         message( "Putting test artifact: " + resourceName + " into test repository " + testRepository );
886 
887         connectWagon( wagon );
888 
889         wagon.put( sourceFile, resourceName );
890 
891         disconnectWagon( wagon );
892 
893         verifyMock( progressArgumentMatcher, content.length() );
894     }
895 
896     protected ProgressArgumentMatcher replayMockForPut( String resourceName, String content, Wagon wagon )
897     {
898         Resource resource = new Resource( resourceName );
899         mockTransferListener.transferInitiated(
900             createTransferEvent( wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_PUT,
901                                  sourceFile ) );
902         resource = new Resource( resourceName );
903         resource.setContentLength( content.length() );
904         resource.setLastModified( sourceFile.lastModified() );
905         mockTransferListener.transferStarted(
906             createTransferEvent( wagon, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_PUT,
907                                  sourceFile ) );
908         mockTransferListener.transferProgress(
909             createTransferEvent( wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_PUT,
910                                  sourceFile ), new byte[]{ }, 0 );
911         ProgressArgumentMatcher progressArgumentMatcher = new ProgressArgumentMatcher();
912         mockTransferListenerControl.setMatcher( progressArgumentMatcher );
913 
914         mockTransferListener.debug( null );
915         mockTransferListenerControl.setMatcher( MockControl.ALWAYS_MATCHER );
916         mockTransferListenerControl.setVoidCallable( MockControl.ZERO_OR_MORE );
917 
918         mockTransferListener.transferCompleted(
919             createTransferEvent( wagon, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_PUT,
920                                  sourceFile ) );
921 
922         mockTransferListenerControl.replay();
923         return progressArgumentMatcher;
924     }
925 
926     protected TransferEvent createTransferEvent( Wagon wagon, Resource resource, int eventType, int requestType,
927                                                  File file )
928     {
929         TransferEvent transferEvent = new TransferEvent( wagon, resource, eventType, requestType );
930         transferEvent.setLocalFile( file );
931         return transferEvent;
932     }
933 
934     protected int putFile()
935         throws Exception
936     {
937         String content = "test-resource.txt\n";
938         putFile( resource, "test-resource", content );
939         return content.length();
940     }
941 
942     protected void getFile( int expectedSize )
943         throws Exception
944     {
945         destFile = FileTestUtils.createUniqueFile( getName(), getName() );
946         destFile.deleteOnExit();
947 
948         Wagon wagon = getWagon();
949 
950         ProgressArgumentMatcher progressArgumentMatcher = replaceMockForGet( wagon, expectedSize );
951 
952         message( "Getting test artifact from test repository " + testRepository );
953 
954         connectWagon( wagon );
955 
956         wagon.get( this.resource, destFile );
957 
958         disconnectWagon( wagon );
959 
960         verifyMock( progressArgumentMatcher, expectedSize );
961     }
962 
963     protected void verifyMock( ProgressArgumentMatcher progressArgumentMatcher, int length )
964     {
965         mockTransferListenerControl.verify();
966 
967         assertEquals( length, progressArgumentMatcher.getSize() );
968 
969         mockTransferListenerControl.reset();
970     }
971 
972     protected void disconnectWagon( Wagon wagon )
973         throws ConnectionException
974     {
975         wagon.removeTransferListener( mockTransferListener );
976 
977         wagon.removeTransferListener( checksumObserver );
978 
979         wagon.disconnect();
980     }
981 
982     protected void connectWagon( Wagon wagon )
983         throws ConnectionException, AuthenticationException
984     {
985         wagon.addTransferListener( checksumObserver );
986 
987         wagon.addTransferListener( mockTransferListener );
988 
989         wagon.connect( testRepository, getAuthInfo() );
990     }
991 
992     protected ProgressArgumentMatcher replaceMockForGet( Wagon wagon, int expectedSize )
993     {
994         Resource resource = new Resource( this.resource );
995         mockTransferListener.transferInitiated(
996             createTransferEvent( wagon, resource, TransferEvent.TRANSFER_INITIATED, TransferEvent.REQUEST_GET,
997                                  destFile ) );
998         resource = new Resource( this.resource );
999         resource.setContentLength( getExpectedContentLengthOnGet( expectedSize ) );
1000         resource.setLastModified( getExpectedLastModifiedOnGet( testRepository, resource ) );
1001         TransferEvent te =
1002             createTransferEvent( wagon, resource, TransferEvent.TRANSFER_STARTED, TransferEvent.REQUEST_GET, null );
1003         mockTransferListener.transferStarted( te );
1004         mockTransferListener.transferProgress(
1005             new TransferEvent( wagon, resource, TransferEvent.TRANSFER_PROGRESS, TransferEvent.REQUEST_GET ),
1006             new byte[]{ }, 0 );
1007         ProgressArgumentMatcher progressArgumentMatcher = new ProgressArgumentMatcher();
1008         mockTransferListenerControl.setMatcher( progressArgumentMatcher );
1009 
1010         mockTransferListener.debug( null );
1011         mockTransferListenerControl.setMatcher( MockControl.ALWAYS_MATCHER );
1012         mockTransferListenerControl.setVoidCallable( MockControl.ZERO_OR_MORE );
1013 
1014         mockTransferListener.transferCompleted(
1015             createTransferEvent( wagon, resource, TransferEvent.TRANSFER_COMPLETED, TransferEvent.REQUEST_GET,
1016                                  destFile ) );
1017 
1018         mockTransferListenerControl.replay();
1019         return progressArgumentMatcher;
1020     }
1021 
1022     protected int getExpectedContentLengthOnGet( int expectedSize )
1023     {
1024         return expectedSize;
1025     }
1026 
1027     protected long getExpectedLastModifiedOnGet( Repository repository, Resource resource )
1028     {
1029         // default implementation - prone to failing if the time between test file creation and completion of putFile()
1030         // cross the "second" boundary, causing the "remote" and local files to have different times.
1031 
1032         return sourceFile.lastModified();
1033     }
1034 
1035     protected void fileRoundTripTesting()
1036         throws Exception
1037     {
1038         message( "File round trip testing ..." );
1039 
1040         int expectedSize = putFile();
1041 
1042         assertNotNull( "check checksum is not null", checksumObserver.getActualChecksum() );
1043 
1044         assertEquals( "compare checksums", "6b144b7285ffd6b0bc8300da162120b9", checksumObserver.getActualChecksum() );
1045 
1046         checksumObserver = new ChecksumObserver();
1047 
1048         getFile( expectedSize );
1049 
1050         assertNotNull( "check checksum is not null", checksumObserver.getActualChecksum() );
1051 
1052         assertEquals( "compare checksums", "6b144b7285ffd6b0bc8300da162120b9", checksumObserver.getActualChecksum() );
1053 
1054         // Now compare the conents of the artifact that was placed in
1055         // the repository with the contents of the artifact that was
1056         // retrieved from the repository.
1057 
1058         String sourceContent = FileUtils.fileRead( sourceFile );
1059 
1060         String destContent = FileUtils.fileRead( destFile );
1061 
1062         assertEquals( sourceContent, destContent );
1063     }
1064 
1065     // ----------------------------------------------------------------------
1066     //
1067     // ----------------------------------------------------------------------
1068 
1069     protected Repository createFileRepository( String url )
1070     {
1071         File path = new File( url.substring( 7 ) );
1072 
1073         path.mkdirs();
1074 
1075         Repository repository = new Repository();
1076 
1077         repository.setUrl( url );
1078 
1079         return repository;
1080     }
1081 
1082 }