-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathhuggingface_test.go
More file actions
873 lines (721 loc) · 28.5 KB
/
huggingface_test.go
File metadata and controls
873 lines (721 loc) · 28.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
package main
// HuggingFace Integration Tests
// Run with: go test -v -test.huggingface -jfrog.url=http://localhost:8081/ -jfrog.user=admin -jfrog.password=password
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/jfrog/jfrog-cli-core/v2/utils/config"
"github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"
coreTests "github.com/jfrog/jfrog-cli-core/v2/utils/tests"
"github.com/jfrog/jfrog-cli/utils/tests"
clientTestUtils "github.com/jfrog/jfrog-client-go/utils/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func initHuggingFaceTest(t *testing.T) {
if !*tests.TestHuggingFace {
t.Skip("Skipping HuggingFace test. To run HuggingFace test add the '-test.huggingface=true' option.")
}
if artifactoryCli == nil {
initArtifactoryCli()
}
// Set up home directory configuration so GetDefaultServerConf() can find the server
createJfrogHomeConfig(t, true)
// Initialize serverDetails for HuggingFace tests
serverDetails = &config.ServerDetails{
Url: *tests.JfrogUrl,
ArtifactoryUrl: *tests.JfrogUrl + tests.ArtifactoryEndpoint,
SshKeyPath: *tests.JfrogSshKeyPath,
SshPassphrase: *tests.JfrogSshPassphrase,
}
if *tests.JfrogAccessToken != "" {
serverDetails.AccessToken = *tests.JfrogAccessToken
} else {
serverDetails.User = *tests.JfrogUser
serverDetails.Password = *tests.JfrogPassword
}
}
func cleanHuggingFaceTest(t *testing.T) {
clientTestUtils.UnSetEnvAndAssert(t, coreutils.HomeDir)
clientTestUtils.UnSetEnvAndAssert(t, "HF_ENDPOINT")
clientTestUtils.UnSetEnvAndAssert(t, "HF_TOKEN")
tests.CleanFileSystem()
}
// checkHuggingFaceHubAvailable checks if python3 and huggingface_hub library are available
func checkHuggingFaceHubAvailable(t *testing.T) {
// Check if python3 is available
if _, err := exec.LookPath("python3"); err != nil {
t.Skip("python3 not found in PATH, skipping HuggingFace test")
}
// Check if huggingface_hub library is installed
cmd := exec.Command("python3", "-c", "import huggingface_hub")
if err := cmd.Run(); err != nil {
t.Skip("huggingface_hub library not installed, skipping HuggingFace test. Install with: pip install huggingface_hub")
}
}
// isExpectedUploadError checks if the error is an expected error for upload without credentials or proper setup
// Returns true if the error is expected (authentication, authorization, or infrastructure related), false otherwise
func isExpectedUploadError(err error) bool {
if err == nil {
return false
}
errStr := strings.ToLower(err.Error())
// Expected errors when uploading without proper credentials or HuggingFace remote repo setup
expectedPatterns := []string{
"401",
"403",
"unauthorized",
"authentication",
"permission",
"access denied",
"forbidden",
"credentials",
"token",
"login",
"connection refused",
"client has been closed",
"connection reset",
"no such host",
"timeout",
"timed out",
}
for _, pattern := range expectedPatterns {
if strings.Contains(errStr, pattern) {
return true
}
}
return false
}
// isArtifactoryAuthError checks if the error indicates Artifactory authentication/configuration issues
// This is used to skip tests when HF_ENDPOINT is set but Artifactory isn't properly configured
func isArtifactoryAuthError(err error) bool {
if err == nil {
return false
}
errStr := strings.ToLower(err.Error())
// Check if error mentions Artifactory URL patterns and auth issues
isArtifactoryRelated := strings.Contains(errStr, "artifactory") ||
strings.Contains(errStr, "/api/huggingface/")
isAuthError := strings.Contains(errStr, "401") ||
strings.Contains(errStr, "unauthorized") ||
strings.Contains(errStr, "authentication")
return isArtifactoryRelated && isAuthError
}
// uploadTestModelToLocalRepo uploads minimal test model files to the local HuggingFace repo
// so that subsequent download tests have something to retrieve.
func uploadTestModelToLocalRepo(t *testing.T, jfrogCli *coreTests.JfrogCli, repoID string) {
t.Helper()
tempDir, err := os.MkdirTemp("", "hf-local-setup-*")
require.NoError(t, err, "Setup: failed to create temp dir")
t.Cleanup(func() { _ = os.RemoveAll(tempDir) })
require.NoError(t, os.WriteFile(filepath.Join(tempDir, "config.json"), []byte(`{"model_type":"test"}`), 0644))
require.NoError(t, os.WriteFile(filepath.Join(tempDir, "model.bin"), []byte("test model binary content"), 0644))
args := []string{
"hf", "u", tempDir, repoID,
"--repo-type=model",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
require.NoError(t, jfrogCli.Exec(args...), "Setup: upload to local repo failed for "+repoID)
}
// uploadTestDatasetToLocalRepo uploads minimal test dataset files to the local HuggingFace repo.
func uploadTestDatasetToLocalRepo(t *testing.T, jfrogCli *coreTests.JfrogCli, repoID string) {
t.Helper()
tempDir, err := os.MkdirTemp("", "hf-local-dataset-setup-*")
require.NoError(t, err, "Setup: failed to create temp dir for dataset")
t.Cleanup(func() { _ = os.RemoveAll(tempDir) })
require.NoError(t, os.WriteFile(filepath.Join(tempDir, "train.json"), []byte(`[{"text":"sample training data"}]`), 0644))
require.NoError(t, os.WriteFile(filepath.Join(tempDir, "test.json"), []byte(`[{"text":"sample test data"}]`), 0644))
args := []string{
"hf", "u", tempDir, repoID,
"--repo-type=dataset",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
require.NoError(t, jfrogCli.Exec(args...), "Setup: upload dataset to local repo failed for "+repoID)
}
// TestHuggingFaceDownload tests the HuggingFace download command
func TestHuggingFaceDownload(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
repoID := "test-org/test-model"
// Upload test files to the local repo first
uploadTestModelToLocalRepo(t, jfrogCli, repoID)
// Download from the local repo
args := []string{
"hf", "d", repoID,
"--repo-type=model",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err := jfrogCli.Exec(args...)
assert.NoError(t, err, "HuggingFace download command should succeed")
}
// TestHuggingFaceDownloadWithRevision tests the HuggingFace download command with revision parameter
func TestHuggingFaceDownloadWithRevision(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
repoID := "test-org/test-model-revision"
// Upload test files to the local repo first (uploaded to default 'main' branch)
uploadTestModelToLocalRepo(t, jfrogCli, repoID)
// Download from the local repo specifying revision=main
args := []string{
"hf", "d", repoID,
"--repo-type=model",
"--revision=main",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err := jfrogCli.Exec(args...)
assert.NoError(t, err, "HuggingFace download with revision should succeed")
}
// TestHuggingFaceDownloadDataset tests the HuggingFace download command for datasets
func TestHuggingFaceDownloadDataset(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
repoID := "test-org/test-dataset"
// Upload test dataset files to the local repo first
uploadTestDatasetToLocalRepo(t, jfrogCli, repoID)
// Download the dataset from the local repo
args := []string{
"hf", "d", repoID,
"--repo-type=dataset",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err := jfrogCli.Exec(args...)
assert.NoError(t, err, "HuggingFace download dataset should succeed")
}
// TestHuggingFaceDownloadWithEtagTimeout tests the HuggingFace download command with etag-timeout
func TestHuggingFaceDownloadWithEtagTimeout(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
repoID := "test-org/test-model-etag"
// Upload test files to the local repo first
uploadTestModelToLocalRepo(t, jfrogCli, repoID)
// Download from the local repo with etag-timeout parameter
args := []string{
"hf", "d", repoID,
"--repo-type=model",
"--etag-timeout=3600",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err := jfrogCli.Exec(args...)
assert.NoError(t, err, "HuggingFace download with etag-timeout should succeed")
}
// TestHuggingFaceUpload tests the HuggingFace upload command
func TestHuggingFaceUpload(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
// Create a temporary directory with test files to upload
tempDir, err := os.MkdirTemp("", "hf-upload-test-*")
require.NoError(t, err, "Failed to create temp directory")
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})
// Create a test file in the temp directory
testFile := filepath.Join(tempDir, "test_model.txt")
err = os.WriteFile(testFile, []byte("test model content"), 0644)
require.NoError(t, err, "Failed to create test model file")
// Create a model config file
configFile := filepath.Join(tempDir, "config.json")
err = os.WriteFile(configFile, []byte(`{"model_type": "test"}`), 0644)
require.NoError(t, err, "Failed to create config file")
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
// Test upload command structure
args := []string{
"hf", "u", tempDir, "test-org/test-model",
"--repo-type=model",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err = jfrogCli.Exec(args...)
// Upload should either succeed (with credentials) or fail with an auth error (without credentials)
if err != nil {
assert.True(t, isExpectedUploadError(err),
"Upload failed with unexpected error: %v. Expected either success or authentication-related error", err)
}
}
// TestHuggingFaceUploadWithRevision tests the HuggingFace upload command with revision parameter
func TestHuggingFaceUploadWithRevision(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
// Create a temporary directory with test files to upload
tempDir, err := os.MkdirTemp("", "hf-upload-revision-test-*")
require.NoError(t, err, "Failed to create temp directory")
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})
// Create a test file in the temp directory
testFile := filepath.Join(tempDir, "test_model.txt")
err = os.WriteFile(testFile, []byte("test model content for revision test"), 0644)
require.NoError(t, err, "Failed to create test model file")
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
// Test upload with revision parameter
args := []string{
"hf", "u", tempDir, "test-org/test-model",
"--repo-type=model",
"--revision=test-branch",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err = jfrogCli.Exec(args...)
// Upload should either succeed (with credentials) or fail with an auth error (without credentials)
if err != nil {
assert.True(t, isExpectedUploadError(err),
"Upload with revision failed with unexpected error: %v. Expected either success or authentication-related error", err)
}
}
// TestHuggingFaceUploadDataset tests the HuggingFace upload command for datasets
func TestHuggingFaceUploadDataset(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
// Create a temporary directory with test dataset files
tempDir, err := os.MkdirTemp("", "hf-upload-dataset-test-*")
require.NoError(t, err, "Failed to create temp directory")
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})
// Create test dataset files
trainFile := filepath.Join(tempDir, "train.json")
err = os.WriteFile(trainFile, []byte(`[{"text": "sample training data"}]`), 0644)
require.NoError(t, err, "Failed to create train file")
testFileData := filepath.Join(tempDir, "test.json")
err = os.WriteFile(testFileData, []byte(`[{"text": "sample test data"}]`), 0644)
require.NoError(t, err, "Failed to create test file")
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
// Test upload dataset
args := []string{
"hf", "u", tempDir, "test-org/test-dataset",
"--repo-type=dataset",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err = jfrogCli.Exec(args...)
// Upload should either succeed (with credentials) or fail with an auth error (without credentials)
if err != nil {
assert.True(t, isExpectedUploadError(err),
"Upload dataset failed with unexpected error: %v. Expected either success or authentication-related error", err)
}
}
// TestHuggingFaceCommandValidation tests that the HuggingFace command properly validates arguments
func TestHuggingFaceCommandValidation(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
// Test download without model name should fail
args := []string{
"hf", "d",
}
err := jfrogCli.Exec(args...)
assert.Error(t, err, "Download without model name should fail")
// Test upload without folder path and repo-id should fail
args = []string{
"hf", "u",
}
err = jfrogCli.Exec(args...)
assert.Error(t, err, "Upload without folder path and repo-id should fail")
// Test upload with only folder path should fail
args = []string{
"hf", "u", "/tmp/test-folder",
}
err = jfrogCli.Exec(args...)
assert.Error(t, err, "Upload with only folder path should fail")
// Test invalid subcommand should fail
args = []string{
"hf", "invalid",
}
err = jfrogCli.Exec(args...)
assert.Error(t, err, "Invalid subcommand should fail")
}
// TestHuggingFaceHelp tests that the HuggingFace help is displayed correctly
func TestHuggingFaceHelp(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
// Test help flag
args := []string{
"hf", "--help",
}
err := jfrogCli.Exec(args...)
assert.NoError(t, err, "Help command should not return error")
}
// TestHuggingFaceDownloadInvalidRepoID tests that download with invalid repo ID returns appropriate error
func TestHuggingFaceDownloadInvalidRepoID(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
// Test download with non-existent repository ID
args := []string{
"hf", "d", "non-existent-org/non-existent-model-12345xyz",
"--repo-type=model",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err := jfrogCli.Exec(args...)
assert.Error(t, err, "Download with invalid repo ID should fail")
// Verify error message contains relevant information
if err != nil {
// If HF_ENDPOINT is set but auth fails, skip the test
if isArtifactoryAuthError(err) {
t.Skipf("Skipping: HF_ENDPOINT is set but Artifactory auth failed: %v", err)
}
errStr := strings.ToLower(err.Error())
hasRelevantError := strings.Contains(errStr, "404") ||
strings.Contains(errStr, "not found") ||
strings.Contains(errStr, "does not exist") ||
strings.Contains(errStr, "repository") ||
strings.Contains(errStr, "couldn't find") ||
strings.Contains(errStr, "locate the files") ||
strings.Contains(errStr, "snapshot folder") ||
strings.Contains(errStr, "error happened")
assert.True(t, hasRelevantError,
"Error should indicate repository not found, got: %v", err)
}
}
// TestHuggingFaceUploadEmptyDirectory tests that upload with empty directory returns appropriate error
func TestHuggingFaceUploadEmptyDirectory(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
// Create an empty temporary directory
tempDir, err := os.MkdirTemp("", "hf-upload-empty-test-*")
require.NoError(t, err, "Failed to create temp directory")
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
// Test upload with empty directory
args := []string{
"hf", "u", tempDir, "test-org/test-empty-model",
"--repo-type=model",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err = jfrogCli.Exec(args...)
// Empty directory upload behavior depends on huggingface_hub - it may succeed or fail
// If it fails, it should be with an appropriate error (not a crash)
if err != nil {
// Verify it's either an auth error or an empty/no files error
errStr := strings.ToLower(err.Error())
isExpected := isExpectedUploadError(err) ||
strings.Contains(errStr, "empty") ||
strings.Contains(errStr, "no files") ||
strings.Contains(errStr, "nothing to upload")
assert.True(t, isExpected,
"Upload empty directory failed with unexpected error: %v", err)
}
}
// TestHuggingFaceUploadNonExistentDirectory tests that upload with non-existent directory returns appropriate error
func TestHuggingFaceUploadNonExistentDirectory(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
// Test upload with non-existent directory
args := []string{
"hf", "u", "/non/existent/path/to/model", "test-org/test-model",
"--repo-type=model",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err := jfrogCli.Exec(args...)
assert.Error(t, err, "Upload with non-existent directory should fail")
// Verify error message indicates path issue
if err != nil {
errStr := strings.ToLower(err.Error())
hasPathError := strings.Contains(errStr, "not found") ||
strings.Contains(errStr, "no such file") ||
strings.Contains(errStr, "does not exist") ||
strings.Contains(errStr, "path") ||
strings.Contains(errStr, "directory")
assert.True(t, hasPathError,
"Error should indicate path not found, got: %v", err)
}
}
// TestHuggingFaceUploadWithSpecialCharactersInPath tests upload with special characters in folder path
func TestHuggingFaceUploadWithSpecialCharactersInPath(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
// Create a temporary directory with special characters in name
baseDir, err := os.MkdirTemp("", "hf-upload-special-*")
require.NoError(t, err, "Failed to create base temp directory")
t.Cleanup(func() {
_ = os.RemoveAll(baseDir)
})
// Create subdirectory with special characters (spaces and dashes)
specialDir := filepath.Join(baseDir, "model with spaces-and-dashes")
err = os.MkdirAll(specialDir, 0755)
require.NoError(t, err, "Failed to create special character directory")
// Create test files
testFile := filepath.Join(specialDir, "config.json")
err = os.WriteFile(testFile, []byte(`{"model_type": "test-special"}`), 0644)
require.NoError(t, err, "Failed to create test file")
modelFile := filepath.Join(specialDir, "model file with spaces.bin")
err = os.WriteFile(modelFile, []byte("test model binary content"), 0644)
require.NoError(t, err, "Failed to create model file with spaces")
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
// Test upload with special characters in path
args := []string{
"hf", "u", specialDir, "test-org/test-special-chars-model",
"--repo-type=model",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err = jfrogCli.Exec(args...)
// Should either succeed or fail with auth error, not crash due to special characters
if err != nil {
assert.True(t, isExpectedUploadError(err),
"Upload with special characters failed with unexpected error: %v. Expected either success or authentication-related error", err)
}
}
// TestHuggingFaceUploadOverwrite tests uploading the same model twice to verify overwrite behavior
func TestHuggingFaceUploadOverwrite(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
// Create a temporary directory with test files
tempDir, err := os.MkdirTemp("", "hf-upload-overwrite-test-*")
require.NoError(t, err, "Failed to create temp directory")
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})
// Create initial model file
configFile := filepath.Join(tempDir, "config.json")
err = os.WriteFile(configFile, []byte(`{"model_type": "test", "version": 1}`), 0644)
require.NoError(t, err, "Failed to create config file")
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
repoID := "test-org/test-overwrite-model"
// First upload
args := []string{
"hf", "u", tempDir, repoID,
"--repo-type=model",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err = jfrogCli.Exec(args...)
firstUploadErr := err
if err != nil && !isExpectedUploadError(err) {
t.Fatalf("First upload failed with unexpected error: %v", err)
}
// Update the model file
err = os.WriteFile(configFile, []byte(`{"model_type": "test", "version": 2}`), 0644)
require.NoError(t, err, "Failed to update config file")
// Second upload (overwrite)
err = jfrogCli.Exec(args...)
secondUploadErr := err
// Both uploads should have same behavior (both succeed or both fail with auth)
if firstUploadErr == nil {
assert.NoError(t, secondUploadErr, "Second upload (overwrite) should also succeed")
} else if isExpectedUploadError(firstUploadErr) {
// If first failed with auth, second should too
if secondUploadErr != nil {
assert.True(t, isExpectedUploadError(secondUploadErr),
"Second upload failed with unexpected error: %v", secondUploadErr)
}
}
}
// TestHuggingFaceDownloadWithBuildInfo tests download with build info collection
func TestHuggingFaceDownloadWithBuildInfo(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
repoID := "test-org/test-model-buildinfo"
// Upload test files to the local repo first
uploadTestModelToLocalRepo(t, jfrogCli, repoID)
buildName := tests.HuggingFaceBuildName + "-download"
buildNumber := "1"
// Download from the local repo with build info flags
args := []string{
"hf", "d", repoID,
"--repo-type=model",
"--build-name=" + buildName,
"--build-number=" + buildNumber,
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err := jfrogCli.Exec(args...)
assert.NoError(t, err, "HuggingFace download with build info should succeed")
t.Cleanup(func() {
_ = jfrogCli.Exec("rt", "build-discard", buildName, "--max-builds=0")
})
}
// TestHuggingFaceUploadWithBuildInfo tests upload with build info collection
func TestHuggingFaceUploadWithBuildInfo(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
// Create a temporary directory with test files
tempDir, err := os.MkdirTemp("", "hf-upload-buildinfo-test-*")
require.NoError(t, err, "Failed to create temp directory")
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})
// Create test files
configFile := filepath.Join(tempDir, "config.json")
err = os.WriteFile(configFile, []byte(`{"model_type": "test-buildinfo"}`), 0644)
require.NoError(t, err, "Failed to create config file")
modelFile := filepath.Join(tempDir, "model.bin")
err = os.WriteFile(modelFile, []byte("test model content for build info"), 0644)
require.NoError(t, err, "Failed to create model file")
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
buildName := tests.HuggingFaceBuildName + "-upload"
buildNumber := "1"
// Test upload with build info flags
args := []string{
"hf", "u", tempDir, "test-org/test-buildinfo-model",
"--repo-type=model",
"--build-name=" + buildName,
"--build-number=" + buildNumber,
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err = jfrogCli.Exec(args...)
// Upload should either succeed (with credentials) or fail with auth error
if err != nil {
assert.True(t, isExpectedUploadError(err),
"Upload with build info failed with unexpected error: %v. Expected either success or authentication-related error", err)
}
// Clean up build info
t.Cleanup(func() {
// Attempt to clean build info (may fail if not created, which is fine)
_ = jfrogCli.Exec("rt", "build-discard", buildName, "--max-builds=0")
})
}
// TestHuggingFaceDownloadWithBuildInfoAndModule tests download with build info and module
func TestHuggingFaceDownloadWithBuildInfoAndModule(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
repoID := "test-org/test-model-module"
// Upload test files to the local repo first
uploadTestModelToLocalRepo(t, jfrogCli, repoID)
buildName := tests.HuggingFaceBuildName + "-download-module"
buildNumber := "1"
moduleName := "test-model-module"
// Download from the local repo with build info and module flags
args := []string{
"hf", "d", repoID,
"--repo-type=model",
"--build-name=" + buildName,
"--build-number=" + buildNumber,
"--module=" + moduleName,
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err := jfrogCli.Exec(args...)
assert.NoError(t, err, "HuggingFace download with build info and module should succeed")
t.Cleanup(func() {
_ = jfrogCli.Exec("rt", "build-discard", buildName, "--max-builds=0")
})
}
// TestHuggingFaceUploadWithBuildInfoAndProject tests upload with build info and project
func TestHuggingFaceUploadWithBuildInfoAndProject(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
// Check if python3 and huggingface_hub are available
checkHuggingFaceHubAvailable(t)
// Create a temporary directory with test files
tempDir, err := os.MkdirTemp("", "hf-upload-project-test-*")
require.NoError(t, err, "Failed to create temp directory")
t.Cleanup(func() {
_ = os.RemoveAll(tempDir)
})
// Create test files
configFile := filepath.Join(tempDir, "config.json")
err = os.WriteFile(configFile, []byte(`{"model_type": "test-project"}`), 0644)
require.NoError(t, err, "Failed to create config file")
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
buildName := tests.HuggingFaceBuildName + "-upload-project"
buildNumber := "1"
projectKey := "test-project"
// Test upload with build info and project flags
args := []string{
"hf", "u", tempDir, "test-org/test-project-model",
"--repo-type=model",
"--build-name=" + buildName,
"--build-number=" + buildNumber,
"--project=" + projectKey,
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err = jfrogCli.Exec(args...)
// Upload should either succeed (with credentials) or fail with auth/project error
if err != nil {
errStr := strings.ToLower(err.Error())
isExpected := isExpectedUploadError(err) ||
strings.Contains(errStr, "project") ||
strings.Contains(errStr, "not found")
assert.True(t, isExpected,
"Upload with project failed with unexpected error: %v", err)
}
// Clean up build info
t.Cleanup(func() {
_ = jfrogCli.Exec("rt", "build-discard", buildName, "--max-builds=0", "--project="+projectKey)
})
}
// TestHuggingFaceDownloadAndVerifyCache tests downloading a model and verifying files are cached
func TestHuggingFaceDownloadAndVerifyCache(t *testing.T) {
initHuggingFaceTest(t)
defer cleanHuggingFaceTest(t)
checkHuggingFaceHubAvailable(t)
jfrogCli := coreTests.NewJfrogCli(execMain, "jfrog", "")
repoID := "test-org/test-model-cache"
// Upload test files to the local repo first
uploadTestModelToLocalRepo(t, jfrogCli, repoID)
// Download from the local repo
args := []string{
"hf", "d", repoID,
"--repo-type=model",
"--repo-key=" + tests.HuggingFaceLocalRepo,
}
err := jfrogCli.Exec(args...)
if err != nil {
t.Skipf("Download failed, skipping file verification: %v", err)
}
// Verify files are cached under ~/.cache/huggingface/hub/
homeDir, err := os.UserHomeDir()
require.NoError(t, err, "Failed to get user home directory")
hfCacheDir := filepath.Join(homeDir, ".cache", "huggingface", "hub")
if _, err := os.Stat(hfCacheDir); os.IsNotExist(err) {
t.Log("HuggingFace cache directory not found at default location, skipping file verification")
return
}
found := false
err = filepath.Walk(hfCacheDir, func(path string, info os.FileInfo, walkErr error) error {
if walkErr != nil {
return filepath.SkipDir
}
if strings.Contains(path, "test-model-cache") {
found = true
return filepath.SkipDir
}
return nil
})
require.NoError(t, err, "Failed to walk cache directory")
assert.True(t, found, "Downloaded model files should exist in HuggingFace cache")
}
// InitHuggingFaceTests initializes HuggingFace tests
func InitHuggingFaceTests() {
initArtifactoryCli()
cleanUpOldBuilds()
cleanUpOldRepositories()
tests.AddTimestampToGlobalVars()
createRequiredRepos()
}
// CleanHuggingFaceTests cleans up after HuggingFace tests
func CleanHuggingFaceTests() {
deleteCreatedRepos()
}